#include "dialog_gh.h"
#include "ui_dialog_gh.h"
#include "pub_var.h"
#include <QDebug>
#include <QMessageBox>
#include <QAbstractItemView>
#include <QScrollBar>
#include <QSqlError>
#include <QFile>
#include <QPrinterInfo>
#include <QDateTime>
#include <QPageSize>
#include <QCryptographicHash>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>

Dialog_gh::Dialog_gh(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog_gh)
{
    ui->setupUi(this);

    initialed = false;
    //禁止dialog 窗口的默认按钮。
    ui->pbDefault->setVisible(false);

    //恢复窗口上次关闭时的位置和大小
    QSettings setIni("clin.ini", QSettings::IniFormat);
    QRect rct = setIni.value("windowState/gh").toRect();
    this->setGeometry(rct);
    qApp->processEvents();  //刷新界面显示

    /*
    //使用读卡器原厂动态库
    //如果存在读卡器库，调用。
    qDebug()<<"检查路径中是否存在身份证读卡器dll。";
    QFile f;
    QString k = setIni.value("cardreader/use").toString();
    QString dllFile = QCoreApplication::applicationDirPath();
    dllFile.append("/IDdlls/Termb.dll");

    if(f.exists(dllFile) && k == "1"){ //读卡器动态库存在且允许使用
        lib.setFileName("IDdlls/Termb");
        if(lib.load()){
            CVR_InitComm  = (pCVR_InitComm)lib.resolve("CVR_InitComm");//initialize
            CVR_Authenticate = (pCVR_Authenticate)lib.resolve("CVR_Authenticate") ;//卡认证;
            CVR_Read_Content = (pCVR_Read_Content)lib.resolve("CVR_Read_Content") ;//读卡操作。
            CVR_CloseComm = (pCVR_CloseComm)lib.resolve("CVR_CloseComm") ;//关闭连接;
            GetPeopleName = (pGetPeopleName)lib.resolve("GetPeopleName") ;//得到姓名信息
            GetPeopleSex = (pGetPeopleSex)lib.resolve("GetPeopleSex") ;//得到性别信息
            GetSexCode = (pGetSexCode)lib.resolve("GetSexCode") ;//得到性别信息
            GetPeopleBirthday = (pGetPeopleBirthday)lib.resolve("GetPeopleBirthday") ;//得到出生日期
            GetPeopleIDCode = (pGetPeopleIDCode)lib.resolve("GetPeopleIDCode") ;//得到卡号信息

            iniCardReader(setIni.value("cardreader/port").toInt());

        }else{
            QMessageBox::information(NULL, "注意","身份证读卡器动态库无效！");
            haveCardReader = false;
            ui->pbDsfz->setEnabled(false);
            qDebug()<<"身份证读卡器动态库无效！";
        }
    }else{
        ui->pbDsfz->setEnabled(false);
        qDebug()<<"身份证读卡器动态库不存在或被禁止使用！";
    }

*/
    qrm = new QSqlQuery(pub::db_m);
    qro = new QSqlQuery(pub::db_o);
    qro1 = new QSqlQuery(pub::db_o);

    //界面显示挂号科室的行数、列数
    dpRows = setIni.value("gh/rows").toInt();
    dpColumns = setIni.value("gh/columns").toInt();

    if(dpRows <1 || dpRows > 10 || dpColumns > 10 || dpColumns < 2){
        QMessageBox::information(this,"警告","挂号待选科室行列数设置错误，使用默认5列1行！");
        dpRows = 1;
        dpColumns = 5 ;
    }

    //显示可用挂号科室
    sq = "select dept_code, dept_name, default_diag from com_department where valid_state = '1' and regdept_flag = '1'";
    qro->exec(sq);
    ui->twDpList->setRowCount(dpRows);
    ui->twDpList->setColumnCount(dpColumns);
    for(int r = 0; r < dpRows ; r++){
        for(int c = 0; c< dpColumns; c++){
            if(qro->next()){
                ui->twDpList->setItem(r,c,new QTableWidgetItem(qro->value(1).toString()));
                dept_name_code << qro->value(1).toString() + "^" + qro->value(0).toString()
                                  + "^" + qro->value(2).toString();
            }else{
                ui->twDpList->setItem(r,c,new QTableWidgetItem(""));
            }
        }
    }

    //禁止列表滚动
    ui->twDpList->horizontalScrollBar()->setVisible(false);
    ui->twDpList->verticalScrollBar()->setVisible(false);

    //医生列表
    docRows = setIni.value("gh/drows").toInt();
    docColumns = setIni.value("gh/dcolumns").toInt();
    if(docRows <1 || docRows > 10 || docColumns > 10 || docColumns < 2){
        QMessageBox::information(this,"警告","医生行列数设置错误，使用默认5列1行！");
        docRows = 1;
        docColumns = 5 ;
    }

    ui->twDocList->setRowCount(docRows);
    ui->twDocList->setColumnCount(docColumns);

    this->setWindowTitle("门诊挂号－当前用户－"+pub::usr_name);

    //挂号类别与挂号费列表
    sq = "select  a.reglevl_name,  b.reg_fee 挂号费, b.chck_fee 工本费, "
         "b.diag_fee 诊察费 , a.reglevl_code"
         " from fin_opr_reglevel a , fin_opr_regfeeonpact b "
         " where a.valid_state = '1' and b.pact_code = '2' and "
         " a.reglevl_code = b.reglevl_code order by a.sort_id ";
    qro->exec(sq);

    QStringList t;
    QString s0,s4;
    float s1,s2,s3;
    while(qro->next()){
        s0 = qro->value(0).toString();//挂号类别名称
        s1 = qro->value(1).toFloat();//挂号费
        s2 = qro->value(2).toFloat();//工本
        s3 = qro->value(3).toFloat();//诊查
        s4 = qro->value(4).toString();//挂号类别代码
        t << s0;
        ghlb_ghf << s0 + "^" + QString::asprintf("%.1f",s1) + "^"
                 + QString::asprintf("%.1f",s2) + "^"
                 + QString::asprintf("%.1f",s3) + "^"
                 + QString::asprintf("%.1f",s1 + s2 + s3) + "^" + s4;
    }
    ui->cbbGhlb->addItems(t);

    //检查医保工作环境
    qDebug()<<"pub::useInsurance = "<<pub::useInsurance;
    if(pub::useInsurance){
        ui->pbYbdk->setEnabled(true);
        ui->pbYbsm->setEnabled(true);
    }else{
        ui->pbYbdk->setEnabled(false);
        ui->pbYbsm->setEnabled(false);
    }

    //配置打印机
    QString printerName = setIni.value("gh/printer").toString();

    prt= new QPrinter(QPrinter::HighResolution);
    //prt= new QPrinter(QPrinter::ScreenResolution);
    prt->setPrinterName(printerName);

    sq = "select p_width,p_height from com_printer_setting where p_type = '挂号票' and p_item = '页面'";
    qrm->exec(sq);
    int w = 0, h = 0;
    if(qrm->next()){
        w = qrm->value(0).toInt();
        h = qrm->value(1).toInt();
    }else{
        QMessageBox::information(this,"错误","挂号票打印参数缺失！");
    }

    if( w<30 || h<30 ){
        QMessageBox::information(this,"错误","挂号票打印参数错误：页面数据无效！");
        w = 100 ;
        h = 100;
    }
    QSizeF sz = QSizeF(w,h);
    QPageSize psz(sz,QPageSize::Millimeter,"ghp",QPageSize::FuzzyMatch);
    prt->setPageSize(psz);

    QPageLayout pglot = QPageLayout(prt->pageLayout());
    QRectF szf = pglot.fullRect(QPageLayout::Point);

    int dotPerInch = prt->physicalDpiX();
    ptScale = double(dotPerInch) / 25.4;

    prt->setOrientation(QPrinter::Portrait);      // 纵向打印
    //prt->setOrientation(QPrinter::Landscape);       //横向打印
    prt->setFullPage(true);
    pnt = new QPainter();

    on_pbClrScr_clicked(); //清屏

    qDebug()<<"提取下一个可用的就诊流水号";
    qro->exec("select seq_fin_clinicno.nextval from dual");
    qro->next();

    regClinicCode = qro->value(0).toString();

    if(regClinicCode.isEmpty()){
        QMessageBox::information(this,"错误","申请clinic_code失败！ ");
        return;
    }
    qDebug()<<"regClinicCode"<<regClinicCode;
    //Signal & Slot
    connect(this,SIGNAL(rejected()),this,SLOT(windClose()));
    connect(ui->twDpList, SIGNAL(itemClicked(QTableWidgetItem *)),this,SLOT(twDpList_Clicked(QTableWidgetItem *)));
    connect(ui->pbDsfz,&QPushButton::clicked,this,&Dialog_gh::pbDsfzClicked);   //读身份证
    connect(ui->pbYbdk,&QPushButton::clicked,this,&Dialog_gh::pbYbdkClicked);   //医保读卡
    connect(ui->pbYbsm,&QPushButton::clicked,this,&Dialog_gh::pbYbsmClicked);   //医保扫码
    connect(ui->pbGh,&QPushButton::clicked,this,&Dialog_gh::pbGhClicked);   //挂号
    connect(ui->leBzh,&QLineEdit::returnPressed,this,&Dialog_gh::leBzhRet);   //病志号回车
    //connect(ui->leSfzh,&QLineEdit::returnPressed,this,&Dialog_gh::leSfzhRet);   //病志号回车

    tm = new QTimer(this);
    connect(tm, SIGNAL(timeout()), this, SLOT(onTimeOut()));

    //初始化医保线程
    qDebug()<<"initialYb thread";
    ybBusiness = new ThreadYb(this);
    ybBusiness->moveToThread(&thread);
    qDebug()<<"thread start";
    thread.start();
    QMetaObject::Connection connRet =  connect(this, SIGNAL(opThread(int, QString)), ybBusiness, SLOT(doWork(int, QString)));
    Q_ASSERT(connRet);

    request.setUrl(QUrl(pub::hos_ybjy));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    //request.setRawHeader("his-code", pub::hos_hiscode.toLatin1());//开发商代码
    //request.setRawHeader("secret-code", pub::hos_secretcode.left(16).toLatin1());//安全管理码

    initialed = true;   //界面初始化标志。防止初始化未完成，发生界面事件。
}

Dialog_gh::~Dialog_gh()
{
    delete ui;
    thread.quit();
    thread.wait();
}

void Dialog_gh::handleRet(const int r, const QString o1,const QString o2)
{
    disconnect(ybBusiness, SIGNAL(resultReady(int, QString, QString)),
               this, SLOT(handleRet(int, QString, QString)));
    businessRetVal = r;
    businessRetStr1 = o1;
    businessRetStr2 = o2;
    businessFinish = true;
}

void Dialog_gh::on_twDocList_itemClicked(QTableWidgetItem * itm)
{
    qDebug()<<"通过医生列表单击提取医生代码";

    if(itm->text().isEmpty()){
        QMessageBox::information(this,"注意","医生姓名无效！");
        return;
    }
    ui->leJzys->setText(itm->text());
    docName = itm->text();
    qro->prepare("select empl_code from com_employee where valid_state = '1' "
                 " and empl_name = :docnm ");
    qro->bindValue(":docnm", docName);
    qro->bindValue(":dpcd", deptCode);
    qro->exec();
    qro->next();
    docCode = qro->value(0).toString();
    if(docCode.isEmpty()){
        QMessageBox::information(this,"注意","医生代码选择无效！");
        return;
    }
    qDebug()<<deptCode<<docName<<docCode;
}

void Dialog_gh::twDpList_Clicked(QTableWidgetItem * itm)
{
    qDebug()<<"诊室列表单击，提取诊室代码和关联医生信息";
    if(itm->text().isEmpty()){
        QMessageBox::information(this,"注意","诊室无效！");
        return;
    }
    ui->leGhzs->setText(itm->text());   //显示选定的诊室
    ui->leJzys->setText("");        //清除选定的医生
    deptName = itm->text();     //查找诊室代码
    foreach(QString i, dept_name_code){
        if(pub::getStr(i,"^",1) == deptName){
            deptCode = pub::getStr(i,"^",2);  //诊室代码
            defaultDeptDiag = pub::getStr(i,"^",3);  //诊室默认诊断
            break;
        }
    }
    selectDoctor();     //按照预定规则选择接诊医生
}

void Dialog_gh::iniCardReader(int pt)
{
    qDebug()<<"初始化身份证读卡器";
    int ret = CVR_InitComm(pt);

    if(ret == 1){   //正常
        haveCardReader = true;
        return;
    }else if(ret == 2){     //端口错
        if(findCardReader()){  //查到有效端口
            return;
        }
    }else if(ret == 0){  //
        QMessageBox::information(NULL,"Note","身份证阅读器动态库运行中发生错误！");
    }else{
        QMessageBox::information(NULL,"Note","身份证阅读器错误，状态未知！");
    }
    haveCardReader = false;
    ui->pbDsfz->setEnabled(false);
}

bool Dialog_gh::findCardReader()
{
    qDebug()<<"检索身份证读卡器是否存在";
    int ret;

    for(int p=1001;p<1010;p++){
        ret = CVR_InitComm(p);

        if(ret == 1){
            haveCardReader = true;
            QSettings setIni("id.ini", QSettings::IniFormat);
            setIni.setValue("cardreader/port",QString::number(p));
            return true;
        }
    }
    QMessageBox::information(NULL,"Note","查询不到有效的身份证阅读器端口！");
    return false;
}

void Dialog_gh::windClose()
{
    qDebug()<<"窗口关闭，保存当前窗口位置";
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/gh", QVariant(this->geometry()));
}

void Dialog_gh::pbDsfzClicked()
{

    mdtrt_cert_type = "02"; //就诊凭证类型

    qDebug()<<"读身份证";

    statusMsg = "医保卡有效性验证。。。";

    connect(ybBusiness, SIGNAL(resultReady(int, QString, QString)),
            this, SLOT(handleRet(int, QString, QString)));


    //卡机开始读卡

    emit opThread(mdtrt_cert_type.toInt() , "QString");    // 发送信号触发线程 , 执行 ReadCardBas

    businessFinish = false;
    while(true){
        QThread::msleep(330);
        if( ui->lbLastRec->text().isEmpty()){
            ui->lbLastRec->setText(statusMsg);
        }else{
            ui->lbLastRec->setText("");
        }
        qApp->processEvents();
        if(businessFinish){
            break;
        }
    }

    if(businessRetVal == 0){

        QString ret1 = businessRetStr1; //获取出参
        QString ret2 = businessRetStr2; //获取出参

        cardInfo = businessRetStr1;
        busiCardInfo= businessRetStr2;
        qDebug()<<"ret1 = "<<ret1;
        qDebug()<<"ret2 = "<<ret2;


        sq = "insert into com_business (ywbh,user,jysj,jyfs,v_in,v_out) values "
             "('idRead','" + pub::usr_code + "',DATE_FORMAT(now(),'%Y-%m-%d %T'),'id','','"
                + ret1 + "^" + ret2 + "')";
        if(!qrm->exec(sq)){
            QMessageBox::information(this,"注意","保存医保动态库交易日志失败！ ");
            qDebug()<<sq;
        }


        QJsonObject in;
        putBaseIn(  in, "1101")        ;

        QJsonObject inpu,inpud;
        QString sfzh;//身份证号

        inpu.insert("mdtrt_cert_type", mdtrt_cert_type);   //就诊凭证类别
        inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",2) + "|" + busiCardInfo);   //社保卡,4卡号3社保号
        inpu.insert("psn_name", pub::getStr(cardInfo,"|",5)); //人员姓名
//        inpu.insert("card_sn",pub::getStr(cardInfo,"|",5)); //卡识别码
        inpu.insert("certno", pub::getStr(cardInfo,"|",2));      //证件号码
        inpu.insert("psn_cert_type","01");       //人员证件类型  固定？
         sfzh = pub::getStr(cardInfo,"|",2);


        inpud.insert("data",inpu);
        in.insert("input", inpud);

        //connect(ybBusiness, SIGNAL(resultReady(int, QString,QString)), this, SLOT(handleRet(int, QString,QString)));
        QJsonDocument indoc ;
        indoc.setObject(in);

        sq = "update com_business set v_in = '" + indoc.toJson(QJsonDocument::Compact) + "'"
             " where jyls = '" + currentMsgid + "'";

        if(!qrm->exec(sq)){
            QMessageBox::information(this,"错误","保存入参日志失败！");
            qDebug()<<sq;
        }


        qDebug()<<" 1101 indoc"<<indoc;

        QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
        connect(naManager, SIGNAL(finished(QNetworkReply*)),
                this, SLOT(postRequestFinished(QNetworkReply*)));


        httpSuccess = false;
        httpFinished = false;
        rpl = naManager->post(request, indoc.toJson());
        qDebug()<<"request 1101 ...";
        statusMsg = "交易1101。。。";
        while(true){
            QThread::msleep(330);
            if( ui->lbLastRec->text().isEmpty()){
                ui->lbLastRec->setText(statusMsg);
            }else{
                ui->lbLastRec->setText("");
            }
            qApp->processEvents();
            if(httpFinished){
                disconnect(naManager, SIGNAL(finished(QNetworkReply*)),
                           this, SLOT(postRequestFinished(QNetworkReply*)));
                qDebug()<<"return request 1101 ...";
                break;
            }
        }
        if(httpSuccess){
            qDebug()<<"1101 return success.";
            readRetVal("");
            //getRegRec("y", personBaseinfo.value("psn_no").toString().right(10)); //读取挂号记录
            getRegRec("y", personBaseinfo.value("psn_no").toString().right(10) , mpPerson["ybGrbh"]); //读取挂号记录

            //readRetVal("");
            //ui->leSfzh->setText(sfzh);
            //ui->leYbkh->setText(personBaseinfo.value("psn_no").toString().right(10));

        }else{
            //发卡地区行政区划代码（卡识别码前6位）|社会保障号码（身份证号）|卡号|卡识别码|姓名|
            //卡复位信息（仅取历史字节）|规范版本|发卡日期|有效期|终端机编号|终端设备号|性别|民族|
            //出生日期|地址|签发机关|照片BASE64|。

            ui->leXm->setText(pub::getStr(cardInfo,"|", 5));
            QString s = pub::getStr(cardInfo,"|", 12);
            //if(s == "1"){
            if(s == "男"){
                ui->rbM->setChecked(true);
            }else{
                ui->rbFM->setChecked(true);
            }

            ui->leSfzh->setText(pub::getStr(cardInfo,"|", 2));

            QStringList sl = pub::getNl(pub::getStr(cardInfo,"|", 14));
            if(!sl.isEmpty()){
                if(sl[0].toInt() >= 70){//
                    ui->cbbGhlb->setCurrentText("免费号");
                }
                ui->leNl->setText(sl[0]+sl[1]);
            }

            cardReaded = true;

            ui->rbX->setChecked(true);
            getRegRec("s",ui->leSfzh->text(),"");
        }

    }else {
        QMessageBox::information(this,"错误","读取身份证失败！ ");
        qDebug()<<"身份证读卡失败";
    }

}
void Dialog_gh::on_leSfzh_returnPressed()
{
    qDebug()<<"手工录入身份证号检索挂号记录";
    ui->rbX->setChecked(true);  //input identify number, it must be cash regist.

    QString idno = ui->leSfzh->text().trimmed();
    if(idno.length() < 18 ){    //无效身份证
        return;
    }
    int s = idno.mid(16,1).toInt();  //gender flag bit
    if( s % 2 == 1){
        ui->rbM->setChecked(true);
    }else{
        ui->rbFM->setChecked(true);
    }

    QStringList sl = pub::getNl(idno.mid(6, 8));
    if(!sl.isEmpty()){
        if(sl[0].toInt() >= 70){//
            ui->cbbGhlb->setCurrentText("免费号");
        }
        ui->leNl->setText(sl[0]+sl[1]);
    }

    getRegRec("s0",ui->leSfzh->text(),"");
}

void Dialog_gh::postRequestFinished(QNetworkReply *)
{
    httpFinished = true;
    QVariant statusCode = rpl->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意","http 请求状态错误: " + statusCode.toString());
        httpSuccess = false;
        return;
    }

    QNetworkReply::NetworkError err = rpl->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意",rpl->errorString());
        httpSuccess = false;
        return;
    }else{
        QByteArray bt = rpl->readAll();
        QString t = QString::fromLocal8Bit(bt);

        QJsonParseError json_error;
        QJsonDocument jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
        if(json_error.error != 0 ){
            QMessageBox::warning(NULL,"注意","返回信息解析错误 " + json_error.errorString());
            httpSuccess = false;
            return;
        }
        qDebug()<< currentInfno+" outDoc "<<jsdc;
        QJsonObject jsob = jsdc.object();

        sq = "update com_business set v_out = '" + jsdc.toJson(QJsonDocument::Compact) + "'"
             " where jyls = '" + currentMsgid + "'";

        if(!qrm->exec(sq)){
            QMessageBox::information(this,"错误","保存出参日志失败！");
            qDebug()<<sq;
        }


        if(jsob.value("infcode").toInt() != 0){
            QString t = jsob.value("err_msg").toString();
            QMessageBox::warning(NULL,"注意",currentInfno+" 交易失败：" + t );
            httpSuccess = false;
            return;
        }

        if(currentInfno == "1101"){
qDebug()<<"http finished 1101 ";
            personBaseinfo = jsob.value("output").toObject().value("baseinfo").toObject();
            personInsuinfo = jsob.value("output").toObject().value("insuinfo")[0].toObject();
            personIdetinfo = jsob.value("output").toObject().value("idetinfo")[0].toObject();
        }else if(currentInfno == "2201"){
            ret2201 = jsob.value("output").toObject().value("data").toObject();
qDebug()<<"http finished 2201 "            ;
        }else if(currentInfno == "2001"){
            ret2001 = jsob.value("output").toObject().value("trtinfo").toObject();
qDebug()<<"http finished 2001 ";
        }else if(currentInfno == "2203A"){

qDebug()<<"http finished 2203A, 2203A has no return. ";
        }else if(currentInfno == "2204"){
            ret2204 = jsob.value("output").toObject().value("result").toArray();
qDebug()<<"http finished 2204. ";
            for(int i = 0; i< ret2204.size();i++){
                qDebug()<<ret2204[i].toObject().value("feedetl_sn").toString()
                       <<ret2204[i].toObject().value("det_item_fee_sumamt").toString();
            }
        }else if(currentInfno == "2206A"){
            ret2206setlinfo = jsob.value("output").toObject().value("setlinfo").toObject();
            ret2206setldetail = jsob.value("output").toObject().value("setldetail").toObject();
qDebug()<<ret2206setlinfo.value("acct_pay").toString()<<ret2206setldetail.value("setl_proc_info").toString();
qDebug()<<"http finished 2206 ";
        }else if(currentInfno == "2207A"){
            ret2207setlinfo = jsob.value("output").toObject().value("setlinfo").toObject();
            ret2207setldetail = jsob.value("output").toObject().value("setldetail").toObject();
qDebug()<<ret2207setlinfo.value("acct_pay").toString()<<ret2207setldetail.value("setl_proc_info").toString();
qDebug()<<"http finished 2207 ";
        }else if(currentInfno == "1901"){
            QJsonArray r = jsob.value("output").toObject().value("list").toArray();
            qDebug()<<r[0].toObject().value("type").toString();
        }

        httpSuccess = true;
    }
}

void Dialog_gh::pbYbdkClicked()
{
    mdtrt_cert_type = "03"; //就诊凭证类型

    qDebug()<<"通过读卡器读医保卡信息";

    statusMsg = "医保卡有效性验证。。。";

    connect(ybBusiness, SIGNAL(resultReady(int, QString, QString)),
            this, SLOT(handleRet(int, QString, QString)));


    //卡机开始读卡

    emit opThread(mdtrt_cert_type.toInt() , "QString");    // 发送信号触发线程 , 执行 ReadCardBas

    businessFinish = false;
    while(true){
        QThread::msleep(330);
        if( ui->lbLastRec->text().isEmpty()){
            ui->lbLastRec->setText(statusMsg);
        }else{
            ui->lbLastRec->setText("");
        }
        qApp->processEvents();
        if(businessFinish){
            break;
        }
    }

    if(businessRetVal == 0){

        QString ret1 = businessRetStr1; //获取出参
        QString ret2 = businessRetStr2; //获取出参
        //cardInfo = businessRetStr1.right(businessRetStr1.length()-2);
        cardInfo = businessRetStr1;
        busiCardInfo= businessRetStr2;
        qDebug()<<"ret1 = "<<ret1;
        qDebug()<<"ret2 = "<<ret2;


        sq = "insert into com_business (ywbh,user,jysj,jyfs,v_in,v_out) values "
             "('cardRead','" + pub::usr_code + "',DATE_FORMAT(now(),'%Y-%m-%d %T'),'card','','"
                + ret1 + "^" + ret2 + "')";
        if(!qrm->exec(sq)){
            QMessageBox::information(this,"注意","保存医保动态库交易日志失败！ ");
            qDebug()<<sq;
        }


        QJsonObject in;
        putBaseIn(  in, "1101")        ;

        QJsonObject inpu,inpud;
        QString sfzh;//身份证号

        inpu.insert("mdtrt_cert_type", mdtrt_cert_type);   //就诊凭证类别
        if( "1" == pub::getStr(cardInfo,"|",1) ) {   //0 社保卡， 1 老医保卡
            if(pub::getStr(cardInfo,"|",8).isEmpty()){
                inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",9) + "|" + busiCardInfo);//老医保卡,8卡号9社保号
            }else{
                inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",8) + "|" + busiCardInfo);//老医保卡,8卡号9社保号
            }
            sfzh = pub::getStr(cardInfo,"|",9);
            inpu.insert("psn_name", pub::getStr(cardInfo,"|",10)); //人员姓名
            inpu.insert("card_sn",pub::getStr(cardInfo,"|",2)); //卡识别码
            inpu.insert("certno", pub::getStr(cardInfo,"|",9));      //证件号码
            inpu.insert("psn_cert_type","01");       //人员证件类型  固定？
        } else {
            inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",4) + "|" + busiCardInfo);   //社保卡,4卡号3社保号
            inpu.insert("psn_name", pub::getStr(cardInfo,"|",6)); //人员姓名
            inpu.insert("card_sn",pub::getStr(cardInfo,"|",5)); //卡识别码
            inpu.insert("certno", pub::getStr(cardInfo,"|",3));      //证件号码
            inpu.insert("psn_cert_type","01");       //人员证件类型  固定？
            sfzh = pub::getStr(cardInfo,"|",3);
        }

        inpud.insert("data",inpu);
        in.insert("input", inpud);

        //connect(ybBusiness, SIGNAL(resultReady(int, QString,QString)), this, SLOT(handleRet(int, QString,QString)));
        QJsonDocument indoc ;
        indoc.setObject(in);

        sq = "update com_business set v_in = '" + indoc.toJson(QJsonDocument::Compact) + "'"
             " where jyls = '" + currentMsgid + "'";

        if(!qrm->exec(sq)){
            QMessageBox::information(this,"错误","保存入参日志失败！");
            qDebug()<<sq;
        }


        qDebug()<<" 1101 indoc"<<indoc;

        QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
        connect(naManager, SIGNAL(finished(QNetworkReply*)),
                this, SLOT(postRequestFinished(QNetworkReply*)));


        httpSuccess = false;
        httpFinished = false;
        rpl = naManager->post(request, indoc.toJson());
        qDebug()<<"request 1101 ...";
        statusMsg = "交易1101。。。";
        while(true){
            QThread::msleep(330);
            if( ui->lbLastRec->text().isEmpty()){
                ui->lbLastRec->setText(statusMsg);
            }else{
                ui->lbLastRec->setText("");
            }
            qApp->processEvents();
            if(httpFinished){
                disconnect(naManager, SIGNAL(finished(QNetworkReply*)),
                           this, SLOT(postRequestFinished(QNetworkReply*)));
                qDebug()<<"return request 1101 ...";
                break;
            }
        }
        if(httpSuccess){
            qDebug()<<"1101 return success.";
            readRetVal("");
            //为兼容新旧格式，检索两种格式的医保个人编号
            getRegRec("y", personBaseinfo.value("psn_no").toString().right(10) , mpPerson["ybGrbh"]); //读取挂号记录

            //readRetVal("");
            //ui->leSfzh->setText(sfzh);
            //ui->leYbkh->setText(personBaseinfo.value("psn_no").toString().right(10));

        }else{

        }

    }else {
        QMessageBox::information(this,"错误","医保读卡失败！ ");
        qDebug()<<"医保读卡失败";
    }

}

void Dialog_gh::pbYbsmClicked()
{
    qDebug()<<"读医保二维码";
    mdtrt_cert_type = "01"; //就诊凭证类型

    statusMsg = "医保卡有效性验证。。。";

    connect(ybBusiness, SIGNAL(resultReady(int, QString, QString)),
            this, SLOT(handleRet(int, QString, QString)));


    //开始读卡

    QJsonDocument d;    //清空QJsonObject之用
    QJsonObject in; //入参
    QJsonObject inpu,inpud; // 入参 input 段
    QJsonDocument indoc;

    inpu.insert("businessType", "01101");     //用码类型，挂号
    inpu.insert("officeId", pub::dp_code);
    inpu.insert("officeName", pub::dp_name);
    inpu.insert("operatorId", pub::usr_code);
    inpu.insert("operatorName", pub::usr_name);
    inpu.insert("orgId", pub::hos_ybbh);

    in.insert("data", inpu);

    in.insert("orgId", pub::hos_ybbh);
    in.insert("transType", "ec.query");

    indoc.setObject(in);

    emit opThread(mdtrt_cert_type.toInt() , indoc.toJson());    // 发送信号触发线程

    qDebug()<<"扫码 "<<indoc;

    businessFinish = false;
    while(true){
        QThread::msleep(330);
        if( ui->lbLastRec->text().isEmpty()){
            ui->lbLastRec->setText(statusMsg);
        }else{
            ui->lbLastRec->setText("");
        }
        qApp->processEvents();
        if(businessFinish){
            break;
        }
    }

    if(businessRetVal == 0){

        QString ret1 = businessRetStr1; //获取出参

        QJsonParseError json_error;
        QJsonDocument jsdc = QJsonDocument::fromJson(ret1.toUtf8(), &json_error);
        if(json_error.error != 0 ){
            QMessageBox::warning(NULL,"注意","返回信息解析错误 " + json_error.errorString());
            return ;
        }
        qDebug()<< "scan code outDoc "<<jsdc;

        sq = "insert into com_business (ywbh,user,jysj,jyfs,v_in,v_out) values "
             "('codeScan','" + pub::usr_code + "',DATE_FORMAT(now(),'%Y-%m-%d %T'),'code','"
                + indoc.toJson(QJsonDocument::Compact) + "','" + ret1 + "')";
        if(!qrm->exec(sq)){
            QMessageBox::information(this,"注意","保存医保动态库交易日志失败！ ");
            qDebug()<<sq;
        }

        QJsonObject jsob = jsdc.object();

        if( !qFuzzyCompare(jsob.value("code").toDouble() , 0)){
            QMessageBox::information(this,"注意","动态库返回失败: " + jsob.value("message").toString());
            return;
        }

        retScan = jsob.value("data").toObject();

qDebug()<<"retScan"<<retScan;

        QJsonObject in;
        putBaseIn(  in, "1101")        ;

        QJsonObject inpu,inpud;
        QString sfzh;//身份证号

        inpu.insert("mdtrt_cert_type", mdtrt_cert_type);   //就诊凭证类别

        inpu.insert("mdtrt_cert_no", retScan.value("ecToken").toString());   //社保卡,4卡号3社保号
        inpu.insert("psn_name", retScan.value("userName").toString()); //人员姓名
        //inpu.insert("card_sn", retScan.value("ecToken").toString()); //卡识别码
        inpu.insert("certno", retScan.value("idNo").toString() );      //证件号码
        inpu.insert("psn_cert_type","01");       //人员证件类型  固定？
        sfzh = retScan.value("idNo").toString();

        inpud.insert("data",inpu);
        in.insert("input", inpud);

        //connect(ybBusiness, SIGNAL(resultReady(int, QString,QString)), this, SLOT(handleRet(int, QString,QString)));
        QJsonDocument indoc ;
        indoc.setObject(in);

        sq = "update com_business set v_in = '" + indoc.toJson(QJsonDocument::Compact) + "'"
             " where jyls = '" + currentMsgid + "'";

        if(!qrm->exec(sq)){
            QMessageBox::information(this,"错误","保存入参日志失败！");
            qDebug()<<sq;
        }
        qDebug()<<" 1101 indoc"<<indoc;

        QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
        connect(naManager, SIGNAL(finished(QNetworkReply*)),
                this, SLOT(postRequestFinished(QNetworkReply*)));


        httpSuccess = false;
        httpFinished = false;
        rpl = naManager->post(request, indoc.toJson());
        qDebug()<<"request 1101 ...";
        statusMsg = "交易1101。。。";
        while(true){
            QThread::msleep(330);
            if( ui->lbLastRec->text().isEmpty()){
                ui->lbLastRec->setText(statusMsg);
            }else{
                ui->lbLastRec->setText("");
            }
            qApp->processEvents();
            if(httpFinished){
                disconnect(naManager, SIGNAL(finished(QNetworkReply*)),
                           this, SLOT(postRequestFinished(QNetworkReply*)));
                qDebug()<<"return request 1101 ...";
                break;
            }
        }
        if(httpSuccess){
            qDebug()<<"1101 return success.";
            readRetVal("");
            //getRegRec("y", personBaseinfo.value("psn_no").toString().right(10)); //读取挂号记录
            getRegRec("y", personBaseinfo.value("psn_no").toString().right(10) , mpPerson["ybGrbh"]); //读取挂号记录

            //readRetVal("");
            //ui->leSfzh->setText(sfzh);
            //ui->leYbkh->setText(personBaseinfo.value("psn_no").toString().right(10));

        }else{

        }

    }else {
        QMessageBox::information(this,"错误","医保扫码失败！ ");
        qDebug()<<"医保扫码失败";
    }

}

void Dialog_gh::pbGhClicked()
{
    qDebug()<<"确认保存挂号信息";
    if(!isValid()){
        return;
    }
    ui->pbGh->setEnabled(false);  //开始收费流程，按钮禁用。
    qApp->processEvents();  //刷新显示

    s.clear();  //票面内容
    char errorText[128];
    for(int i = 0; i<128; i++){
        errorText[i] = '0';
    }
    char fpChar[12];
    for(int i = 0; i<12; i++){
        fpChar[i] = '0';
    }
    int errorCode = 0;

    qDebug()<<"申请发票号";
    ui->lbLastRec->setText("申请发票号");
    qApp->processEvents();  //刷新显示
    qro->prepare("CALL PRC_GET_INVOICENO(  'R', :oper, 50, :ivno, :errtext, :errcode, '')");
    qro->bindValue(":oper", pub::usr_code );//操作员Id
    qro->bindValue(":ivno", fpChar, QSql::Out);   //发票号码
    qro->bindValue(":errtext", errorText, QSql::Out);   //错误内容
    qro->bindValue(":errcode", errorCode, QSql::Out);    //错误编号
    qro->exec();
    QString a,b,c;
    a = qro->boundValue(":ivno").toString();
    b = qro->boundValue(":errtext").toString();
    c = qro->boundValue(":errcode").toString();

    if( a.isEmpty()){
        QMessageBox::information(this,"错误", "申请发票号失败：" + b );
        ui->pbGh->setEnabled(true);  //恢复按钮状态
        return;
    }
    if(c == "101"){
        QMessageBox::information(this,"注意", "未用发票数量低，请及时请领！" );
    }
    QString fph = a;//发票号
    cur_fph = fph;
    qDebug()<<"fph"<<fph;
    s << QString("发票号") + "^" + fph;// pub::add0(fph,10);
    s << QString("名头") + "^" + pub::hos_name;
    s << QString("挂号票") + "^" + "(挂号票)";
    s << QString("挂号日期") + "^" + QDate().currentDate().toString("yyyy-MM-dd");
    s << QString("门诊号") + "^" + ui->leBzh->text();
    s << QString("姓名") + "^" + ui->leXm->text();
    s << QString("性别") + "^" + (ui->rbM->isChecked() ? "男" : "女");
    s << QString("年龄") + "^" + ui->leNl->text();
    s << QString("合计") + "^" + ui->leYsk->text() + "元";
    s << QString("科室") + "^" + ui->leGhzs->text();
    s << QString("挂号类别") + "^" + ui->cbbGhlb->currentText();
    s << QString("挂号时间") + "^" + QDateTime().currentDateTime().toString("HH:mm:ss");
    s << QString("收费类别") + "^" + (ui->rbY->isChecked() ? "医保" : "现金");
    s << QString("大写") + "^" + pub::bigW(ui->leYsk->text().toDouble());
    s << QString("项目明细") + "^" + ui->leGhfmx->text();
    s << QString("操作员") + "^" + pub::usr_code;
    s << QString("接诊医师") + "^" + docName;
    //以下为非打印项目
    s << QString("reglevl_code") + "^" + ghCode;
    s << QString("reg_fee") + "^" + ghGhf;
    s << QString("diag_fee") + "^" + ghZcf;
    s << QString("oth_fee") + "^" + ghGbf;
    s << QString("chck_fee") + "^" + "0";

    //提交医保
    if(pub::useInsurance && ui->rbY->isChecked()){
        ui->lbLastRec->setText("提交医保挂号数据");
        qApp->processEvents();  //刷新显示
        qDebug()<<"医保环境可用，使用医保挂号";
        QString r = ybGh();
        if(r.isEmpty()){    //医保操作异常
            qDebug()<<"医保挂号失败";
            ui->pbGh->setEnabled(true);  //恢复按钮状态
            return;
        }
qDebug()<<"return from ybGh()";
        //返回参数： 费用总额, 帐户支付金额, 现金支付金额, 统筹支付金额, 医疗类别
        s << QString("own_cost") + "^"
             + QString::asprintf("%.2f", ret2207setlinfo.value("psn_cash_pay").toDouble()); //现金支付
        s << QString("pub_cost") + "^"
             + QString::asprintf("%.2f", ret2207setlinfo.value("hifp_pay").toDouble());   //统筹支付
        s << QString("pay_cost") + "^"
             + QString::asprintf("%.2f", ret2207setlinfo.value("acct_pay").toDouble());   //账户支付

qDebug()<<"ret2207setlinfo"<<ret2207setlinfo;
qDebug()<<ret2207setlinfo.value("psn_cash_pay").toDouble();

        ui->leYskX->setText(QString::asprintf("%.2f", ret2207setlinfo.value("psn_cash_pay").toDouble()));
        ui->leYskY->setText(QString::asprintf("%.2f", ret2207setlinfo.value("acct_pay").toDouble()));

        QString t = "现金：" + ui->leYskX->text() + " 医保：" + ui->leYskY->text() + " 余额：";
        int ybys = ui->leYskY->text().toDouble() * 100;    //医保应收
        int ybye = mpPerson["ybZhye"].toDouble() * 100;                //医保账户余额
        if(ybye >= ybys){  //余额充足
            ybye = ybye - ybys;
        }else{
            ybye = 0;
        }
        t.append( QString::asprintf("%.2f", double(ybye) / 100)); //
        s << QString("医保明细") + "^" + t ;
        mpPerson["Inpatient_No"] = regClinicCode;
        mpPerson["Invoice_No"] = fph;
        mpPerson["Card_No"] = ui->leBzh->text();
        mpPerson["Tot_Cost"] = ui->leYsk->text();
        mpPerson["Dept_Code"] = deptCode;
        mpPerson["Dept_Name"] = deptName;
        mpPerson["Own_Cost"] = QString::asprintf("%.2f", ret2207setlinfo.value("psn_cash_pay").toDouble()); //现金支付
        mpPerson["Pub_Cost"] = QString::asprintf("%.2f", ret2207setlinfo.value("hifp_pay").toDouble());   //统筹支付
        mpPerson["Pay_Cost"] = QString::asprintf("%.2f", ret2207setlinfo.value("acct_pay").toDouble());   //账户支付
        mpPerson["trans_type"] = "1"; //挂号正交易
        qDebug()<<"willSaveSi";
        ui->lbLastRec->setText("保存医保相关数据");
        qApp->processEvents();  //刷新显示
        saveSI();
    }else{
        qDebug()<<"现金挂号";
        s << QString("own_cost") + "^" + ui->leYsk->text(); //现金
        s << QString("pub_cost") + "^" + "0";   //统筹
        s << QString("pay_cost") + "^" + "0";   //账户
        ui->leYskX->setText(ui->leYsk->text());
        ui->leYskY->setText("0");
        s << QString("医保明细") + "^" +  "现金 " + ui->leYsk->text() ;    //现金挂号，只打印应收款
    }
    qDebug()<<"保存挂号信息";
    ui->lbLastRec->setText("保存挂号主表信息");
    qApp->processEvents();  //刷新显示
    save(s);
    qDebug()<<"打印挂号票";
    ui->lbLastRec->setText("打印挂号票");
    qApp->processEvents();  //刷新显示
    printOut(s);
    qDebug()<<"清屏";
    on_pbClrScr_clicked(); //清屏
    //取下一个就诊流水号
    qro->exec("select seq_fin_clinicno.nextval from dual");
    qro->next();

    regClinicCode = qro->value(0).toString();

    if(regClinicCode.isEmpty()){
        QMessageBox::information(this,"错误","申请clinic_code失败！ ");
        ui->pbGh->setEnabled(true);  //恢复按钮状态
        return;
    }
    ui->pbGh->setEnabled(true);  //恢复按钮状态
    qDebug()<<"取下一个可用的clinic_code"<<regClinicCode;
}

void Dialog_gh::readRetVal(QString s)
{
    //读取扫码或读卡返回的医保数据
    mpPerson.clear();
    if(mdtrt_cert_type == "03"){    //
        if( "1" == pub::getStr(cardInfo,"|",1) ){   //0 社保卡， 1 老医保卡
            mpPerson["ybGrbh"] = pub::getStr(cardInfo,"|",8);//老医保卡,8卡号9社保号
            if(mpPerson["ybGrbh"].isEmpty()){
                mpPerson["ybGrbh"] = pub::getStr(cardInfo,"|",9);
            }
        }else{
            mpPerson["ybGrbh"] = pub::getStr(cardInfo,"|",4);//社保卡,4卡号3社保号
        }
    }
    if(mdtrt_cert_type == "02"){

        mpPerson["ybGrbh"] = pub::getStr(cardInfo,"|",2);   //身份证号

    }
    if(mdtrt_cert_type == "01"){
        //人员编号后10位即相当于医保卡号
        mpPerson["ybGrbh"] = personBaseinfo.value("psn_no").toString().right(10);

    }
    //mpPerson["ybDwbh"] = pub::getStr(s,"|",2);//单位编号 VARHCAR2(16)
    mpPerson["ybSfzh"] = personBaseinfo.value("certno").toString();
    mpPerson["ybXm"] = personBaseinfo.value("psn_name").toString();
    mpPerson["ybXb"] = personBaseinfo.value("gend").toString();
    mpPerson["ybCsrq"] = personBaseinfo.value("brdy").toString();
    mpPerson["ybSbkh"] = personBaseinfo.value("psn_no").toString();
    //mpPerson["ybYldylb"] = pub::getStr(s,"|",9);//医疗待遇类别 VARHCAR2(3) 二级代码
    //mpPerson["ybYlzh"] = pub::getStr(s,"|",10);//医疗证号 VARHCAR2(20)
    //mpPerson["ybCbzt"] = pub::getStr(s,"|",11);//参保状态 VARHCAR2(3)二级代码 0未参保，1正常，2暂停，3终止
    //mpPerson["ybYdry"] = pub::getStr(s,"|",12);//异地人员标志 VARHCAR2(3) 二级代码 0本地，1异地
    //mpPerson["ybTcqh"] = pub::getStr(s,"|",13);//统筹区号 VARHCAR2(6)
    //mpPerson["ybXzlx"] = pub::getStr(s,"|",14);//险种类型 VARHCAR2(14) 参加医疗保险险种串
    //mpPerson["ybZyzt"] = pub::getStr(s,"|",16);//在院状态 VARHCAR2(1) 二级代码 0不在，1在院
    double zhye = personInsuinfo.value("balc").toDouble();
    mpPerson["ybZhye"] = QString::asprintf("%.2F", zhye);

    //mpPerson["ybZjlx"] = pub::getStr(s,"|",26);//证件类型 VARHCAR2(2) 二级代码
    //mpPerson["ybLp"] = pub::getStr(s,"|",27);//令牌 VARHCAR2(40)用于业务处理验证

    ui->leXm->setText(mpPerson["ybXm"]);
    if(mpPerson["ybXb"] == "1" || mpPerson["ybXb"] == "M"){
        ui->rbM->setChecked(true);
    }else{
        ui->rbFM->setChecked(true);
    }
    ui->leZhye->setText(mpPerson["ybZhye"]);
    ui->leYbkh->setText(mpPerson["ybGrbh"]);
    ui->leSfzh->setText(mpPerson["ybSfzh"]);
    QStringList sl = pub::getNl(mpPerson["ybCsrq"]);
    if(!sl.isEmpty()){
        if(sl[0].toInt() >= 70){//
            ui->cbbGhlb->setCurrentText("免费号");
        }
        ui->leNl->setText(sl[0]+sl[1]);
    }

}

void Dialog_gh::leSfzhRet()
{

}

void Dialog_gh::leBzhRet()
{
    qDebug()<<"使用病志号方式检索"<<ui->leBzh->text();

    if(ui->leBzh->text().isEmpty()){
        qDebug()<<"病志号空";
        return;
    }
    ui->leBzh->setText(pub::add0(ui->leBzh->text().trimmed(),10));
    sq = "select r.name, r.birthday, r.sex_code, r.idenno, r.pact_code, r.mcard_no,"
         "r.dept_name, r.clinic_code, r.doct_name, r.card_type, r.reglevl_name, "
         " to_char(r.reg_date ,'yyyy-mm-dd hh24:mi:ss'), r.ynsee, r.valid_flag, r.rowid"
         " from fin_opr_register r "
         " where r.trans_type = '1' and r.card_no = '" + ui->leBzh->text() + "' "
         " order by r.reg_date desc"; //and r.dept_code like '%" + deptCode + "%'
    //对应病志号最后一条有效挂号记录。
    if(!qro->exec(sq)){
        QMessageBox::information(this,"error","SQL is : "+sq);
        qDebug()<<"error"<<sq;
        return;
    }
    qro->next();
    if(qro->isNull(0)){
        qDebug()<<"此病志号没有挂号记录"<<ui->leBzh->text();
        //on_pbClrScr_clicked(); //清屏
        return;
    }


    //
    if(mpPerson["ybXm"].isEmpty()){
       mpPerson["ybXm"] = qro->value(0).toString();//姓名
    }
    if(mpPerson["ybCsrq"].isEmpty()){   //
        if(ui->leSfzh->text().length() == 18){  //身份证号有效，从身份证号提取出生日期。
            mpPerson["ybCsrq"] = ui->leSfzh->text().mid(6,8);
        }else{//使用上次挂号数据
            QDate dt = qro->value(1).toDate();
            mpPerson["ybCsrq"] = dt.toString("yyyyMMdd");//出生日期
        }

    }
    if(mpPerson["ybXb"].isEmpty()){
        mpPerson["ybXb"] = qro->value(2).toString();//性别  二级代码 1 男 2 女
        (mpPerson["ybXb"] == "M" || mpPerson["ybXb"] == "1") ? ui->rbM->setChecked(true) : ui->rbFM->setChecked(true);    //sex
    }


    //mpPerson["ybSfzh"] = qro->value(3).toString();//身份证号
    //regPact = qro->value(4).toString(); //二级代码，1 现金， 2 医保
    //mpPerson["ybGrbh"] = qro->value(5).toString();//个人编号,医保卡号 VARHCAR2(16)
    deptName = qro->value(6).toString();    //last regist department
    //mpPerson["ybZjlx"] = qro->value(9).toString();//证件类型 VARHCAR2(2) 二级代码
    //ui->cbbGhlb->setCurrentText(qro->value(10).toString());  //挂号类别，普通，免费，。。
    QString lastRec = "最近挂号：" + deptName + " " +  qro->value(11).toString();
    ui->lbLastRec->setText(lastRec);


    //yb = "";
    //mpPerson["ybLp"] = "";
    /*  不依据历史挂号记录设置本次挂号方式
    if(regPact == "1"){ //现金挂号
        ui->rbX->setChecked(true);
    }else if(regPact == "2"){   //医保挂号
        ui->rbY->setChecked(true);
    }else{
        QMessageBox::information(this,"错误","缴费方式非现金非医保！");
        return ;
    }
    */

    if(ui->leXm->text().isEmpty()){
        ui->leXm->setText(mpPerson["ybXm"]); //name
    }

    QStringList ag = pub::getNl(mpPerson["ybCsrq"]);
    qDebug()<< "age is "<<ag;
    qDebug()<< "ui->leNl->text() is "<<ui->leNl->text();
    qDebug()<< "ui->cbbGhlb->currentText() is "<<ui->cbbGhlb->currentText();
    if(ui->leNl->text().isEmpty()){

        if(ag[0].toInt() >= 70){//
            ui->cbbGhlb->setCurrentText("免费号");
        }
        ui->leNl->setText(ag[0]+ag[1]);     //age
    }



    if(ui->leSfzh->text().isEmpty()){
        if(mpPerson["ybSfzh"].isEmpty()){
            mpPerson["ybSfzh"] = qro->value(3).toString();    //身份证号
        }
        ui->leSfzh->setText(mpPerson["ybSfzh"]); //identify card

    }

    if(ui->leYbkh->text().isEmpty()){
        ui->leYbkh->setText(mpPerson["ybGrbh"]);     //card number
    }

    ui->leGhzs->setText(deptName);
    qDebug()<<"检索挂号科室代码";
    foreach(QString i, dept_name_code){ //
        if(pub::getStr(i,"^",1) == deptName){
            deptCode = pub::getStr(i,"^",2);  //代码
            defaultDeptDiag = pub::getStr(i,"^",3);  //诊室默认诊断
            break;
        }
    }
    qDebug()<<"设置医生列表";
    qDebug()<<"病志号存在历史挂号记录，设置界面模式为retbzh";
    setState("retbzh");

    if( "0" == qro->value(12).toString() && "1" == qro->value(13).toString()){  //最后一个号有效且未用
        ui->pbGhtp->setEnabled(true);
        mpPerson["rowid"] = qro->value(14).toString();
        mpPerson["previous_doct_name"] = qro->value(8).toString();
        mpPerson["previous_dept_name"] = deptName;
        mpPerson["previous_patient_name"] = qro->value(0).toString();
    }
    selectDoctor(); //

}

void Dialog_gh::printOut(QStringList p)
{
    qDebug()<<"打印挂号票";
    //参数格式： type^val
    //mode = 1 打印 item + val, mode = 0 只打印val
    QString item, val, mode,print_item,font;
    QFont ft=QFont();
    int top,left,width,height,size,position;

    pnt->begin(prt);
    foreach(QString i , p){
        item = pub::getStr(i, "^", 1);
        val = pub::getStr(i, "^", 2);

        sq = "select p_top,p_left,p_width,p_height,p_font_name,p_font_size,p_position,p_mode,p_print_item from com_printer_setting "
             " where p_type = '挂号票' and p_item = '"+item+"'";
        if(!qrm->exec(sq)){
            QMessageBox::information(this,"error","SQL is : "+sq);
            return;
        }

        qrm->next();
        if(qrm->isNull(0)){
            //QMessageBox::information(this,"错误","找不到指定的项目名称："+item+" - "+val);
            continue;   //非打印项目
        }

        top = qrm->value(0).toInt();
        left = qrm->value(1).toInt();
        width = qrm->value(2).toInt();
        height = qrm->value(3).toInt();
        font = qrm->value(4).toString();
        size = qrm->value(5).toDouble();
        position = qrm->value(6).toInt();
        mode = qrm->value(7).toString();
        print_item = qrm->value(8).toString();
        //ft.setPointSize(int(ptScale * size));
        ft.setPixelSize(int(ptScale * size));
        ft.setFamily(font);

        pnt->setFont(ft);

        const QRect rect = QRect( left * ptScale, top * ptScale, width * ptScale, height * ptScale);
        QRect boundingRect;

        if(mode == "1"){
            pnt->drawText(rect, position, print_item + ":" + val, &boundingRect);
        }else{
            pnt->drawText(rect, position, val, &boundingRect);
        }
    }
    pnt->end();
}

void Dialog_gh::on_cbbGhlb_currentTextChanged(QString s)
{
    qDebug()<<"挂号类别变更";
    readGhf(s);
}

void Dialog_gh::readGhf(QString s)
{
    qDebug()<<"检索当前挂号类别挂号费" << s;
    foreach(QString i, ghlb_ghf){
        if(pub::getStr(i,"^",1) == s){
            qDebug() << i;
            ui->leYsk->setText(pub::getStr(i,"^",5));
            ghGhf = pub::getStr(i,"^",2);   //挂号费
            ghGbf = pub::getStr(i,"^",3);   //工本费
            ghZcf = pub::getStr(i,"^",4);   //诊查费
            ghType = pub::getStr(i,"^",1);  //当前挂号类别
            ghCode = pub::getStr(i,"^",6);  //类别代码
            ui->leGhfmx->setText("挂号费：" +  ghGhf +
                                 "，工本费：" + ghGbf +
                                 "，诊察费：" + ghZcf );
            break;
        }
    }
}

void Dialog_gh::save(QStringList s)
{
    qDebug()<<"save 保存挂号数据"<<ui->leBzh->text();
    sq = "select card_no from com_patientinfo where card_no ='" + ui->leBzh->text() + "'";
    qro->exec(sq);

    if(!qro->next()){  //
        qDebug()<<"查询返回空，首诊患者，保存记录到 com_patientinfo";
        qro->prepare("insert into com_patientinfo (pact_name,idenno,card_no,name,birthday,sex_code,pact_code,"
                    "fir_see_date,oper_code,oper_date) values (:pact_name,:idenno,:card_no,:name,:birthday,"
                    ":sex_code,:pact_code,sysdate,:oper_code,sysdate)");
        qro->bindValue(":card_no", ui->leBzh->text());
        qro->bindValue(":idenno", ui->leSfzh->text());
        qro->bindValue(":name", ui->leXm->text());
        //qro->bindValue(":birthday", QDate::fromString(pub::getBirth(ui->leNl->text()),"yyyyMMdd"));
        if(ui->leSfzh->text().length() == 18){  //身份证号有效，从身份证号提取出生日期。否则从年龄估算。
            qro->bindValue(":birthday", QDate::fromString(ui->leSfzh->text().mid(6,8),"yyyyMMdd"));
        }else{
            qro->bindValue(":birthday", QDate::fromString(pub::getBirth(ui->leNl->text()),"yyyyMMdd"));
        }

        qro->bindValue(":sex_code", ui->rbM->isChecked() ? "M" : "F");
        qro->bindValue(":pact_code", ui->rbX->isChecked() ? "1" : "2");
        qro->bindValue(":pact_name", ui->rbX->isChecked() ? "现金" : "沈阳市保");
        qro->bindValue(":oper_code", pub::usr_code);

        if(!qro->exec()){
            QMessageBox::information(this,"错误","插入数据表“com_patientinfo”错误！");
            qDebug()<<qro->lastError().text();
            qDebug()<<qro->executedQuery();
        }
    }

    //recipe_no，日结必须要有这个字段
    sq = "select name from com_dictionary where oper_code = '" + pub::usr_code + "' and type = 'RegRecipeNo'";
    qro->exec(sq);
    qro->next();
    QString regRecNo = qro->value(0).toString();
    qro->prepare("update com_dictionary set name = :name where oper_code = :oper  and type = 'RegRecipeNo'");
    qro->bindValue(":oper",pub::usr_code);
    qro->bindValue(":name",QString::number(regRecNo.toInt() + 1));
    qro->exec();
    qDebug()<<"recipe_no"<<QString::number(regRecNo.toInt() + 1);

    qDebug()<<"保存记录到 fin_opr_register";
    qro->prepare("insert into fin_opr_register (balance_flag,recipe_no,clinic_code,trans_type,card_no,reg_date,name,"
                 "idenno,sex_code,birthday,card_type,paykind_code,pact_code,pact_name,"
                 "mcard_no,reglevl_code,"
                 "reglevl_name,dept_code,dept_name,order_no,seeno,invoice_no,"
                 "reg_fee,chck_fee,diag_fee,oth_fee,own_cost,pub_cost,pay_cost,valid_flag,oper_code,"
                 "oper_date, ynsee, doct_code, doct_name) "
                 "values "
                 "('0',:recipe_no,:clinic_code,'1',:card_no,sysdate,:name,:idenno,:sex_code,"
                 ":birthday,:card_type,concat('0',:pact_code),:pact_code,:pact_name,:mcard_no,"
                 ":reglevel_code,:reglevl_name,"
                 ":dept_code,:dept_name,get_reg_sn('ALL'),get_reg_sn(:dept_code),:invoice_no,:reg_fee,"
                 ":chck_fee,:diag_fee,:oth_fee,:own_cost,:pub_cost,:pay_cost,'1',:oper_code,sysdate,'0',"
                 ":doct_code, :doct_name)");
    qro->bindValue(":recipe_no", regRecNo);
    qro->bindValue(":clinic_code", regClinicCode);
    qro->bindValue(":card_no", ui->leBzh->text());
    qro->bindValue(":name", ui->leXm->text());
    qro->bindValue(":idenno", ui->leSfzh->text());
    qro->bindValue(":sex_code", ui->rbM->isChecked() ? "M" : "F");
    //qro->bindValue(":birthday", QDate::fromString(pub::getBirth(ui->leNl->text()),"yyyyMMdd"));
    if(ui->leSfzh->text().length() == 18){  //身份证号有效，从身份证号提取出生日期。否则从年龄估算。
        qro->bindValue(":birthday", QDate::fromString(ui->leSfzh->text().mid(6,8),"yyyyMMdd"));
    }else{
        qro->bindValue(":birthday", QDate::fromString(pub::getBirth(ui->leNl->text()),"yyyyMMdd"));
    }
    qro->bindValue(":card_type", "01");
    qro->bindValue(":pact_code", ui->rbX->isChecked() ? "1" : "2");
    qro->bindValue(":pact_name", ui->rbX->isChecked() ? "现金" : "沈阳市保");
    qro->bindValue(":mcard_no", ui->leYbkh->text());
    qro->bindValue(":reglevel_code", ghCode);
    qro->bindValue(":reglevl_name", ghType);
    qro->bindValue(":dept_code", deptCode);
    qro->bindValue(":dept_name", deptName);
    qro->bindValue(":doct_code", docCode);
    qro->bindValue(":doct_name", docName);
    qro->bindValue(":invoice_no", pub::getValueFromList(s, "发票号"));
    qro->bindValue(":reg_fee", pub::getValueFromList(s, "reg_fee"));
    qro->bindValue(":chck_fee", pub::getValueFromList(s, "chck_fee"));
    qro->bindValue(":diag_fee", pub::getValueFromList(s, "diag_fee"));
    qro->bindValue(":oth_fee", pub::getValueFromList(s, "oth_fee"));

    qro->bindValue(":own_cost", pub::getValueFromList(s, "own_cost"));
    qro->bindValue(":pub_cost", pub::getValueFromList(s, "pub_cost"));
    qro->bindValue(":pay_cost", pub::getValueFromList(s, "pay_cost"));
    qro->bindValue(":oper_code", pub::usr_code);



    //qro->bindValue(":own_cost", ret2207setlinfo.value("psn_cash_pay").toDouble());
    //qro->bindValue(":own_cost",ui->leYsk->text());
    //qro->bindValue(":pub_cost", ret2207setlinfo.value("hifp_pay").toDouble());
    //qro->bindValue(":pay_cost", ret2207setlinfo.value("acct_pay").toDouble());

    //qro->bindValue(":own_cost", pub::getValueFromList(s, "own_cost"));
    //qro->bindValue(":pub_cost", pub::getValueFromList(s, "pub_cost"));
    //qro->bindValue(":pay_cost", pub::getValueFromList(s, "pay_cost"));

    //qro->bindValue(":oper_code", pub::usr_code);

    if(!qro->exec()){
        QMessageBox::information(this,"错误","插入数据表“fin_opr_register”错误！");
        qDebug()<<qro->lastError().text();
        qDebug()<<qro->executedQuery();
    }

}

void Dialog_gh::on_pbClrScr_clicked()
{

    qDebug()<<"清屏，初始化窗口工作状态";
    mpPerson.clear();//个人信息
    setState("new");

    ui->leGhzs->clear();
    ui->leJzys->clear();
    ui->leNl->clear();
    ui->leSfzh->clear();
    ui->leXm->clear();
    ui->leYbkh->clear();
    ui->leBzh->clear();
    ui->leZhye->clear();
    ui->leYskX->clear();
    ui->leYskY->clear();
    ui->rbX->setChecked(true);
    ui->cbIdNoCheck->setChecked(true);
    ui->cbbGhlb->setCurrentText("普通门诊");
    readGhf("普通门诊");

    for(int r = 0; r < docRows ; r++){
        for(int c = 0; c< docColumns; c++){
            QString s = "";
            ui->twDocList->setItem(r,c,new QTableWidgetItem(s));
        }
    }

    deptCode = "";
    deptName = "";
    ui->lbLastRec->setText("");

    ui->pbGhtp->setEnabled(false);
    ui->leBzh->setFocus();
    ui->leBzh->selectAll();

    if(pub::useInsurance){
        ui->pbYbdk->setEnabled(true);
        ui->pbYbsm->setEnabled(true);
    }else{
        ui->pbYbdk->setEnabled(false);
        ui->pbYbsm->setEnabled(false);
    }

}

bool Dialog_gh::isValid()
{
    qDebug()<<"挂号信息有效性校验";

    if(docCode.isEmpty()){
        QMessageBox::warning(this,"错误","医生代码无效！");
        return false;
    }
    if(docName.isEmpty()){
        QMessageBox::warning(this,"错误","医生姓名无效！");
        return false;
    }
    if(deptCode.isEmpty()){
        QMessageBox::warning(this,"错误","诊室代码无效！");
        return false;
    }
    if(deptName.isEmpty()){
        QMessageBox::warning(this,"错误","诊室名称无效！");
        return false;
    }

    //姓名
    ui->leXm->setText((ui->leXm->text().trimmed()));
    if(ui->leXm->text().isEmpty()) {
        QMessageBox::warning(this,"错误","姓名不可以为空！");
        return false;
    }else if(ui->leXm->text().length()>20) {
        QMessageBox::warning(this,"错误","姓名长度不可以超过20个字符！");
        return false;
    }

    //身份证号有效性验证
    if(ui->cbIdNoCheck->isChecked()){
        //身份证号长度验证
        ui->leSfzh->setText((ui->leSfzh->text().trimmed()));
        if(ui->leSfzh->text().isEmpty()) {
            QMessageBox::warning(this,"错误","身份证号不可以为空！");
            return false;
        }else if(ui->leSfzh->text().length()>18) {
            QMessageBox::warning(this,"错误","身份证号长度不可以超过18个字符！");
            return false;
        }

        char id[20];
        QByteArray id0 = ui->leSfzh->text().toLocal8Bit();
        memcpy(id, id0, id0.size() +1 );

        if(!verifyIdCard(id)){
            QMessageBox::warning(this,"错误","身份证号有效性校验失败！");
            return false;
        }

        //身份证号与选定性别是否一致
        int s = ui->leSfzh->text().mid(16,1).toInt();  //gender flag bit
        if( s % 2 == 1){
            if(ui->rbFM->isChecked()){
                QMessageBox::warning(this,"错误","身份证号性别与挂号性别不一致！");
                return false;
            }

        }else{

            if(ui->rbM->isChecked()){
                QMessageBox::warning(this,"错误","身份证号性别与挂号性别不一致！");
                return false;
            }
        }
    }
    //年龄
    if(ui->leNl->text().isEmpty()){
        QMessageBox::warning(this,"错误","年龄不可以为空！");
        return false;
    }

    //病志号
    ui->leBzh->setText((ui->leBzh->text().trimmed()));
    if(ui->leBzh->text().isEmpty()){
        QMessageBox::warning(this,"错误","病志号不可以为空！");
        return false;
    }else if(ui->leBzh->text().length()>10) {
        QMessageBox::warning(this,"错误","病志号长度不可以超过10个字符！");
        return false;
    }

    //就诊诊室
    if(ui->leGhzs->text().isEmpty() ){
        QMessageBox::information(this,"错误","诊室不可以为空！");
        return false;
    }

    ui->leBzh->setText(pub::add0(ui->leBzh->text().trimmed(),10) );//如病志号格式不规范，修正。
    QRegExp re("^\\d*$");
    if(re.exactMatch(ui->leNl->text())){    //年龄未输入单位，默认为"岁"
        ui->leNl->setText(ui->leNl->text()+"岁");
    }
    if(ui->rbY->isChecked()){   //医保
        if(ui->leYbkh->text().trimmed().isEmpty() ){
            QMessageBox::information(this,"错误","医保挂号，医保卡号不可以为空！");
            return false;
        }
    }
    QString b = pub::getBirth(ui->leNl->text());
    if(b.isEmpty()){    //录入无效年龄
        QMessageBox::information(this,"错误","录入了无效的年龄！");
        return false;
    }

    //是否存在同日同诊室挂号记录
    sq = "select r.name from fin_opr_register r "
         " where r.valid_flag = '1' and r.card_no = '" + ui->leBzh->text() + "' "
         " and r.dept_code = '" + deptCode + "' and trunc(reg_date) = trunc(sysdate) ";
    qro->exec(sq);

    qro->next();
    if(!qro->isNull(0)){
        qDebug()<<qro->value(0).toString();
        QMessageBox::information(this,"错误","同日相同诊室不可以重复挂号！");
        return false;
    }

    //病志号是否已经使用
    sq = "select r.name from fin_opr_register r "
         " where r.valid_flag = '1' and r.card_no = '" + ui->leBzh->text() + "' and rownum = 1";
    qro->exec(sq);

    qro->next();

    if(!qro->isNull(0) && qro->value(0).toString() != ui->leXm->text().trimmed()){
        //病志号关联的姓名非空，且不等于当前录入的姓名
        QMessageBox::information(this,"错误","病志号 " + ui->leBzh->text() + " 已经被患者 " + qro->value(0).toString() + " 使用！");
        return false;
    }

    qDebug()<<"通过验证";
    return true;
}

QString Dialog_gh::ybGh()
{

    QJsonDocument d;    //清空QJsonObject之用
    QJsonObject in; //入参
    QJsonObject inpu,inpud; // 入参 input 段

    putBaseIn(in, "2201");

    inpu.insert("psn_no", personBaseinfo.value("psn_no").toString());   //人员编号
    inpu.insert("insutype", personInsuinfo.value("insutype").toString());   //险种类型
    inpu.insert("begntime",QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));//	开始时间
    inpu.insert("mdtrt_cert_type",mdtrt_cert_type);//	就诊凭证类型
    if(mdtrt_cert_type == "03"){

        if( "1" == pub::getStr(cardInfo,"|",1) ){   //0 社保卡， 1 老医保卡
            if(pub::getStr(cardInfo,"|",8).isEmpty()){
                inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",9) + "|" + busiCardInfo);//老医保卡,8卡号9社保号
            }else{
                inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",8) + "|" + busiCardInfo);//老医保卡,8卡号9社保号
            }
        }else{
            inpu.insert("mdtrt_cert_no",pub::getStr(cardInfo,"|",4) + "|" + busiCardInfo);//	就诊凭证编号
        }


    }else if(mdtrt_cert_type == "02"){
        inpu.insert("mdtrt_cert_no",pub::getStr(cardInfo,"|",2) + "|" + busiCardInfo);//	就诊凭证编号
    }else if(mdtrt_cert_type == "01"){
        inpu.insert("mdtrt_cert_no", retScan.value("ecToken").toString());//	就诊凭证编号
    }
    inpu.insert("ipt_otp_no", regClinicCode);//	住院/门诊号
    sq = "select si_code, empl_name from com_doctor_compare where empl_code = '" + docCode + "'";
    qro->exec(sq);
    qro->next();
    docCodeYb = qro->value(0).toString();

    inpu.insert("atddr_no", docCodeYb);//	医师编码
    inpu.insert("dr_name", qro->value(1).toString());//	医师姓名
    inpu.insert("dept_code", deptCode);//	科室编码
    inpu.insert("dept_name", deptName );//	科室名称
    inpu.insert("caty", "0");//	科别

    inpud.insert("data",inpu);
    in.insert("input", inpud);

    QJsonDocument indoc ;
    indoc.setObject(in);

    sq = "update com_business set v_in = '" + indoc.toJson(QJsonDocument::Compact) + "'"
         " where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    qDebug()<<currentInfno + " indoc"<<indoc;

    QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
    connect(naManager, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(postRequestFinished(QNetworkReply*)));

    httpSuccess = false;
    httpFinished = false;
    rpl = naManager->post(request, indoc.toJson());
    qDebug()<<"request " + currentInfno + " ...";
    statusMsg = "交易 " + currentInfno + " 。。。";
    while(true){
        QThread::msleep(330);
        if( ui->lbLastRec->text().isEmpty()){
            ui->lbLastRec->setText(statusMsg);
        }else{
            ui->lbLastRec->setText("");
        }
        qApp->processEvents();
        if(httpFinished){
            //disconnect(naManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(postRequestFinished(QNetworkReply*)));
            qDebug()<<"return request 2201 ...";
            break;
        }
    }

    if(!httpSuccess){// failure then stop operation;
        return "";//

    }

    in = d.object();
    inpu = d.object();
    inpud = d.object();
    putBaseIn(in, "2203A");

    inpu.insert("mdtrt_id", ret2201.value("mdtrt_id").toString());   //就诊ID
    inpu.insert("psn_no", personBaseinfo.value("psn_no").toString());   //人员编号
    inpu.insert("med_type","12");//	医疗类别
    inpu.insert("begntime", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));//	开始时间

    inpud.insert("mdtrtinfo",inpu);
    //in.insert("input", inpud);

    inpu = d.object();
    //    inpud = d.object();

    inpu.insert("diag_type", "1");   //诊断类别：1 西医主要诊断， 2 中医主病诊断	3 中医主证诊断
    inpu.insert("diag_srt_no", 1);   //诊断排序号
    inpu.insert("diag_code", defaultDeptDiag); //诊断代码
    qro->exec("select aka121 from view_ka19 where rownum = 1 and aka120 = '" + defaultDeptDiag + "'");
    qro->next();
    inpu.insert("diag_name", qro->value(0).toString());//诊断名称
    inpu.insert("diag_dept", deptName);   //诊断科室
    inpu.insert("dise_dor_no", docCodeYb);   //诊断医生编码
    inpu.insert("dise_dor_name", docName);//诊断医生姓名
    inpu.insert("diag_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));//诊断时间
    inpu.insert("vali_flag", "1");//有效标志

    QJsonArray djsar;
    djsar<<inpu;

    inpud.insert("diseinfo", djsar);


    in.insert("input", inpud);

    indoc.setObject(in);
    qDebug()<< currentInfno + " indoc"<<indoc;

    sq = "update com_business set v_in = '" + indoc.toJson(QJsonDocument::Compact) + "'"
         " where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }


    //QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
    //connect(naManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(postRequestFinished(QNetworkReply*)));

    httpSuccess = false;
    httpFinished = false;
    rpl = naManager->post(request, indoc.toJson());
    qDebug()<<"request " + currentInfno + " ...";
    statusMsg = "交易 " + currentInfno + " 。。。";
    while(true){
        QThread::msleep(330);
        if( ui->lbLastRec->text().isEmpty()){
            ui->lbLastRec->setText(statusMsg);
        }else{
            ui->lbLastRec->setText("");
        }
        qApp->processEvents();
        if(httpFinished){
            //disconnect(naManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(postRequestFinished(QNetworkReply*)));
            qDebug()<<"return request " + currentInfno + " ...";
            break;
        }
    }

    if(!httpSuccess){// failure then stop operation;
        return "";//

    }


    //挂号费用上传
    in = d.object();
    inpu = d.object();
    inpud = d.object();
    putBaseIn(in, "2204");

    QJsonArray jsar;
    QString feedetl_sn = "0";
    qro->exec("select max(Balance_No) from fin_ipr_siinmaininfo "
              " where clinic_code = '" + regClinicCode + "'");
    if(qro->next()){
        feedetl_sn = QString::number(qro->value(0).toInt() + 1);
    }


    inpu.insert("feedetl_sn", feedetl_sn);//	费用明细流水号
    inpu.insert("mdtrt_id", ret2201.value("mdtrt_id").toString());//	就诊ID
    inpu.insert("psn_no", personBaseinfo.value("psn_no").toString());//	人员编号
    inpu.insert("chrg_bchno", cur_fph);//	收费批次号
    //inpu.insert("rxno", personBaseinfo.value("psn_no").toString());//	处方号
    inpu.insert("rx_circ_flag", "0");//	外购处方标志
    inpu.insert("fee_ocur_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));//	费用发生时间
    qro->exec("select fee_code_center, fee_code_his from FIN_OPR_REGFEEITEM"
              " where fee_name ='诊查费'");
    qro->next();

    inpu.insert("med_list_codg", qro->value(0).toString());//	医疗目录编码-00110200001000003
    inpu.insert("medins_list_codg", qro->value(1).toString() );//	医药机构目录编码
    inpu.insert("det_item_fee_sumamt", ui->leYsk->text().toDouble());//	明细项目费用总额
    inpu.insert("cnt", 1);//	数量
    inpu.insert("pric", ui->leYsk->text().toDouble());//	单价
    inpu.insert("bilg_dept_codg", deptCode);//	开单科室编码
    inpu.insert("bilg_dept_name", deptName);//	开单科室名称
    inpu.insert("bilg_dr_codg", docCodeYb);//	开单医生编码
    inpu.insert("bilg_dr_name", docName);//	开单医师姓名
    inpu.insert("hosp_appr_flag", "1");//	医院审批标志

    jsar.append(inpu);

    inpud.insert("feedetail",jsar);
    in.insert("input", inpud);

    //connect(ybBusiness, SIGNAL(resultReady(int, QString,QString)), this, SLOT(handleRet(int, QString,QString)));

    indoc.setObject(in);
    qDebug()<< currentInfno + " indoc"<<indoc;

    sq = "update com_business set v_in = '" + indoc.toJson(QJsonDocument::Compact) + "'"
         " where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    //QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
    //connect(naManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(postRequestFinished(QNetworkReply*)));


    httpSuccess = false;
    httpFinished = false;
    rpl = naManager->post(request, indoc.toJson());
    qDebug()<<"request " + currentInfno + " ...";
    statusMsg = "交易 " + currentInfno + " 。。。";
    while(true){
        QThread::msleep(330);
        if( ui->lbLastRec->text().isEmpty()){
            ui->lbLastRec->setText(statusMsg);
        }else{
            ui->lbLastRec->setText("");
        }
        qApp->processEvents();
        if(httpFinished){
            // disconnect(naManager, SIGNAL(finished(QNetworkReply*)),  this, SLOT(postRequestFinished(QNetworkReply*)));
            qDebug()<<"retrun request " + currentInfno + " ...";
            break;
        }
    }

    if(!httpSuccess){// failure then stop operation;
        return "";//

    }

/*

    //预结算
    in = d.object();
    inpu = d.object();
    inpud = d.object();
    putBaseIn(in, "2206A");

    inpu.insert("psn_no", personBaseinfo.value("psn_no").toString());//人员编号
    inpu.insert("mdtrt_cert_type", mdtrt_cert_type);//	就诊凭证类型

    if(mdtrt_cert_type == "03"){
        if( "1" == pub::getStr(cardInfo,"|",1) ){   //0 社保卡， 1 老医保卡
            inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",8));//老医保卡,8卡号9社保号
        }else{
            inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",4));   //社保卡,4卡号3社保号
        }
    }else if(mdtrt_cert_type == "02"){

    }else if(mdtrt_cert_type == "01"){

    }

    inpu.insert("med_type", "12");//医疗类别    12,挂号
    inpu.insert("medfee_sumamt", 3);//	医疗费总额
    inpu.insert("psn_setlway", "01");//	个人结算方式
    inpu.insert("mdtrt_id", ret2201.value("mdtrt_id").toString());//	就诊ID
    inpu.insert("chrg_bchno", cur_fph);//	收费批次号
    inpu.insert("acct_used_flag","1" );//个人账户使用标志
    inpu.insert("insutype", personInsuinfo.value("insutype").toString());//险种类型

    QJsonObject t;
    t.insert("deve_flag","OwnSoft");
    t.insert("dise_reim_mon","");

    inpu.insert("exp_content", t);//	字段扩展
    inpud.insert("data",inpu);
    in.insert("input", inpud);



    //connect(ybBusiness, SIGNAL(resultReady(int, QString,QString)), this, SLOT(handleRet(int, QString,QString)));

    indoc.setObject(in);
    qDebug()<< currentInfno + " indoc"<<indoc;
        sq = "update com_business set v_in = '" + indoc.toJson(QJsonDocument::Compact) + "'"
             " where jyls = '" + currentMsgid + "'";

        if(!qrm->exec(sq)){
            QMessageBox::information(this,"错误","保存入参日志失败！");
            qDebug()<<sq;
        }

    //QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
    //connect(naManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(postRequestFinished(QNetworkReply*)));


    httpSuccess = false;
    httpFinished = false;
    rpl = naManager->post(request, indoc.toJson());
    qDebug()<<"request " + currentInfno + " ...";
    statusMsg = "交易 " + currentInfno + " 。。。";
    while(true){
        QThread::msleep(330);
        if( ui->lbLastRec->text().isEmpty()){
            ui->lbLastRec->setText(statusMsg);
        }else{
            ui->lbLastRec->setText("");
        }
        qApp->processEvents();
        if(httpFinished){
            //disconnect(naManager, SIGNAL(finished(QNetworkReply*)),this, SLOT(postRequestFinished(QNetworkReply*)));
            qDebug()<<"retrun request " + currentInfno + " ...";
            break;
        }
    }

*/

    //医保结算
    in = d.object();
    inpu = d.object();
    inpud = d.object();
    putBaseIn(in, "2207A");

    inpu.insert("psn_no", personBaseinfo.value("psn_no").toString());//人员编号
    inpu.insert("mdtrt_cert_type", mdtrt_cert_type);//	就诊凭证类型

    if(mdtrt_cert_type == "03"){
        if( "1" == pub::getStr(cardInfo,"|",1) ){   //0 社保卡， 1 老医保卡

            //inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",8) + "|" + busiCardInfo);//老医保卡,8卡号9社保号
            if(pub::getStr(cardInfo,"|",8).isEmpty()){
                inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",9) + "|" + busiCardInfo);//老医保卡,8卡号9社保号
            }else{
                inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",8) + "|" + busiCardInfo);//老医保卡,8卡号9社保号
            }

        }else{
            inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",4) + "|" + busiCardInfo);   //社保卡,4卡号3社保号
        }
    }else if(mdtrt_cert_type == "02"){
        inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",2) + "|" + busiCardInfo);

    }else if(mdtrt_cert_type == "01"){
        inpu.insert("mdtrt_cert_no", retScan.value("ecToken").toString());//	就诊凭证编号
    }

    inpu.insert("med_type", "12");//医疗类别    12,挂号
    inpu.insert("medfee_sumamt", ui->leYsk->text());//	医疗费总额
    inpu.insert("psn_setlway", "01");//	个人结算方式
    inpu.insert("mdtrt_id", ret2201.value("mdtrt_id").toString());//	就诊ID
    inpu.insert("chrg_bchno", cur_fph);//	收费批次号
    inpu.insert("acct_used_flag","1" );//个人账户使用标志
    inpu.insert("insutype", personInsuinfo.value("insutype").toString());//险种类型

    /*
invono	发票号	字符型	20
fulamt_ownpay_amt	全自费金额	数值型	16,2
overlmt_selfpay	超限价金额	数值型	16,2
preselfpay_amt	先行自付金额	数值型	16,2
inscp_scp_amt	符合政策范围金额	数值型	16,2

*/

    QJsonObject t;
    t.insert("deve_flag","OwnSoft");
    t.insert("dise_reim_mon","");

    inpu.insert("exp_content", t);//	字段扩展
    inpud.insert("data",inpu);
    in.insert("input", inpud);



    //connect(ybBusiness, SIGNAL(resultReady(int, QString,QString)), this, SLOT(handleRet(int, QString,QString)));

    indoc.setObject(in);
    qDebug()<<" 2207 indoc"<<indoc;

    sq = "update com_business set v_in = '" + indoc.toJson(QJsonDocument::Compact) + "'"
         " where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    //QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
    //connect(naManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(postRequestFinished(QNetworkReply*)));


    httpSuccess = false;
    httpFinished = false;
    rpl = naManager->post(request, indoc.toJson());
    qDebug()<<"request " + currentInfno + " ...";
    statusMsg = "交易 " + currentInfno + " 。。。";
    while(true){
        QThread::msleep(330);
        if( ui->lbLastRec->text().isEmpty()){
            ui->lbLastRec->setText(statusMsg);
        }else{
            ui->lbLastRec->setText("");
        }
        qApp->processEvents();
        if(httpFinished){
            //disconnect(naManager, SIGNAL(finished(QNetworkReply*)),this, SLOT(postRequestFinished(QNetworkReply*)));
            qDebug()<<"retrun request " + currentInfno + " ...";
            break;
        }
    }
    if(httpSuccess){
        return "success";
    }else{
        return "";
    }
}

void Dialog_gh::resizeEvent(QResizeEvent *event)
{
    if(!initialed){
        return;
    }
    Q_UNUSED(event);

    int columnWidth=(ui->twDpList->width()-3)/dpColumns;
    for(int c = 0; c<dpColumns; c++){
        ui->twDpList->setColumnWidth(c,columnWidth);
    }

    int rowHeight=(ui->twDpList->height()-3)/dpRows;
    for(int r = 0; r< dpRows; r++){
        ui->twDpList->setRowHeight(r,rowHeight);
    }

    columnWidth=(ui->twDocList->width()-3)/docColumns;
    for(int c = 0; c<docColumns; c++){
        ui->twDocList->setColumnWidth(c,columnWidth);
    }
    rowHeight=(ui->twDocList->height()-3)/docRows;
    qDebug()<<rowHeight<<ui->twDocList->height()<<docRows;
    for(int r = 0; r< docRows; r++){
        ui->twDocList->setRowHeight(r,rowHeight);
    }
    qDebug()<<"窗口界面设定完成";
}

void Dialog_gh::setState(QString s)
{
    qDebug()<<"设置界面工作模式"<<s;
    if(s == "new"){ //
        qDebug()<<"新病志号，所有项目均可录入";
        displayMode = "new";
        ui->leNl->setReadOnly(false);
        ui->leSfzh->setReadOnly(false);
        ui->leXm->setReadOnly(false);
        ui->grpSex->setEnabled(true);
    }else if(s == "retbzh"){    //
        qDebug()<<"病志号检索有效，基础项目不可录入";
        displayMode = "retbzh";
        if(ui->leNl->text().isEmpty()){
            ui->leNl->setReadOnly(false);
        }else{
            ui->leNl->setReadOnly(true);
        }

        if(ui->leSfzh->text().length() < 18){
            ui->leSfzh->setReadOnly(false);
        }else{
            ui->leSfzh->setReadOnly(true);
        }
//        ui->leXm->setReadOnly(true);
        if(mpPerson["ybXb"].isEmpty()){
            ui->grpSex->setEnabled(true);
        }else{
            ui->grpSex->setEnabled(false);
        }
    }
}

void Dialog_gh::getRegRec(QString s, QString n1, QString n2)
{
    //s = “y”  医保卡，s = “s”身份证 ; n 是对应的医保卡号或身份证号;
    qDebug()<<"检索挂号信息， “y”医保卡，“s”身份证 "<<s<<n1<<n2;
    QString sq;
    if(s == "y"){   //医保卡
        ui->rbY->setChecked(true);
        sq = "select card_no from fin_opr_register where mcard_no = '"+ n1 +"' or mcard_no = '"+ n2 +"' order by reg_date desc";
    }else if(s == "s" || s == "s0"){ //身份证,s 机读， s0手工录入。
        ui->rbX->setChecked(true);
        sq = "select card_no ,mcard_no from fin_opr_register where idenno = '"+ n1 +"' order by reg_date desc";
    }else{
        QMessageBox::information(this,"注意","getRegRec 参数错误！");
        qDebug()<<"getRegRec 参数错误";
        return;
    }
    if(!qro->exec(sq)){
        qDebug()<<qro->lastQuery();
    }
    if(qro->next()){    //取得有效病志号
        ui->leBzh->setText(qro->value(0).toString());
        qDebug()<<"读取历史挂号信息"<<ui->leBzh->text();
        leBzhRet();
        setState("retbzh"); //有效返回的基础数据不允许修改
        return;
    }

    if( s != "s0"){ //新数据，非手工录入身份证号，不允许修改
        setState("retbzh");
    }
}



void Dialog_gh::selectDoctor()
{
    qDebug()<<"显示医生登录信息";
    //qro->prepare("select empl_name from com_employee where valid_state = '1' and dept_code = :dpcd");
    //qro->bindValue(":dpcd", deptCode);
    sq = "select distinct empl_name from com_loginlog where dept_code ='"
            + deptCode + "' and login_date>trunc(sysdate)";
    qro->exec(sq);
    qDebug()<<"医生所在诊室"<<deptName;

    QStringList nmlst;
    if(!qro->next()){   //未提取到医生登录信息
        qDebug()<<"指定诊室无有效的医生! ";
        QMessageBox::information(this,"注意","指定的科室没有有效医生，请与诊室核对后再挂号！");
        return;
    }else{
        //之前为了判断表是否为空，已经把游标定到0号记录
        while(true){
            QString empl_name = qro->value(0).toString();
            //防止未正常退出登录记录干扰
            sq = "select case when logout_date is not null then '' else empl_name end "
                 "from com_loginlog where empl_name = '"
                    + empl_name + "' and dept_code = '"
                    + deptCode + "' order by login_date desc" ;
            qro1->exec(sq);

            qro1->next();
            if(!qro1->value(0).toString().isEmpty()){
                nmlst << qro1->value(0).toString();
            }
            if(!qro->next()){
                break;
            }
        }
    }

    qDebug()<<"清空用于计算分配接诊医生的临时表";
    qro->exec("delete from sun_doc_reg_count");

    //QString docs = "'doctor'";
    int count = 0;
    for(int r = 0; r < docRows ; r++){
        for(int c = 0; c< docColumns; c++){
            QString s = "";
            if(count < nmlst.size()){
                s = nmlst[count];
                //docs.append(",'"+s+"'");
                qro->exec("insert into sun_doc_reg_count (doc_name, doc_code, ord_count, see_count)"
                          " values('" + s + "', (select empl_code from com_employee where"
                          " empl_name = '" + s + "' and valid_state = '1' and rownum = 1 ), 0 , 0)");      //存储临时表
                count ++;
            }
            ui->twDocList->setItem(r,c,new QTableWidgetItem(s));
        }
    }

    qDebug()<<"分配默认接诊医生:";
    //分配策略：1.谁有空。 2.都有空，谁接的少。 3.每天分两段计算，13:30 为时间分隔点。
    //2021-8-16
    //患者量不大，且为防止挂号未就诊不及时退号情况，取消 分配策略 1 。
    QTime cur = QTime::currentTime();
    QTime sep = QTime::fromString("13:30:00","HH:mm:ss");
    QString tmp;
    if(cur > sep){
        tmp = "r.reg_date > trunc(sysdate) + 9/16";
    }else{
        tmp = "r.reg_date > trunc(sysdate)";
    }
/*
//检索已经挂号，尚未接诊数量
    qro->prepare("select r.doct_name, count(*) c from fin_opr_register r"
                 " where trunc(r.reg_date) = trunc(sysdate) and r.trans_type = '1' "
                 " and r.valid_flag ='1' and r.dept_code = :dpcd and r.ynsee = '0'"
                 " group by r.doct_name");
    qro->bindValue(":dpcd", deptCode);
    qro->exec();
    while(qro->next()){
        if(!qro->value(0).toString().isEmpty()){
            qro1->exec("update sun_doc_reg_count set ord_count = " + qro->value(1).toString() +
                       " where doc_name = '"+ qro->value(0).toString() +"'");
        }
    }
*/
    //检索已接诊数量
    qro->prepare("select r.doct_code, count(*) c from fin_opr_register r"
                 " where " + tmp + " and r.trans_type = '1' "
                 " and r.valid_flag ='1' and r.dept_code = :dpcd "
                 " group by r.doct_code" );
                //  ; and r.ynsee = '1'"  //统计全部有效挂号，不分已诊未诊
    qro->bindValue(":dpcd", deptCode);
    qro->exec();
    qDebug()<<qro->lastQuery()<<deptCode;
    while(qro->next()){
        if(!qro->value(0).toString().isEmpty()){
            //sun_doc_reg_count里只保存当前可用医生。
            qro1->exec("update sun_doc_reg_count set see_count = " + qro->value(1).toString() +
                       " where doc_code = '"+ qro->value(0).toString() +"'");

            qDebug()<<"检索已接诊数量"<<qro->value(0).toString()<<qro->value(1).toString();

        }
    }

    //qro->exec("select doc_name,doc_code from sun_doc_reg_count order by ord_count, see_count");

    qro->exec("select doc_name,doc_code,see_count from sun_doc_reg_count order by see_count");
//    qro->next();

    qro->next();
    docCode = qro->value(1).toString();
    docName = qro->value(0).toString();
    ui->leJzys->setText(docName);   //默认挑选接诊医生
    qro->exec("insert into sun_tmp (proc,item0,item1,item2,item3) values('selectDoctor','"
              +docCode+"','"+docName+"','"+qro->value(2).toString()
              +"',to_char(sysdate,'yyyy-mm-dd hh24:mi:ss'))");
    qDebug()<<docCode<<docName;

}

void Dialog_gh::saveSI()
{
    qDebug()<<"保存医保相关挂号信息";
    //医保对账需要保存必要信息
    /*
    qro->exec("select max(to_number(BALANCE_NO)) from fin_ipr_siinmaininfo "
              " where inpatient_no = '" + mpPerson["Inpatient_No"] + "'");
    qro->next();
    int blance_no;
    if(qro->value(0).toString().isEmpty()){
        blance_no = 0;
    }else{
        blance_no = qro->value(0).toInt() + 1;
    }
    */
    int blance_no = 0;  //挂号的balance_no只能是 0

    qro->prepare("insert into fin_ipr_siinmaininfo ("
                 " insutype, clr_type, clr_way, hifp_pay, med_type, medfee_sumamt, preselfpay_amt, "
                 " inscp_scp_amt, psn_cash_pay, fund_pay_sumamt, acct_pay, psn_type,"
                 "insuplc_admdvs,psn_no,mdtrt_id,ipt_otp_no,msgid,setl_id,mdtrt_cert_type,"
                 "individualbalance,trans_type,Inpatient_No,"
                 "Balance_No,Invoice_No,Medical_Type,Patient_No,"
                 "Card_No,Mcard_No,App_No,Procreate_Pcno,Si_Begindate,Si_State,Name,"
                 "Sex_Code,Idenno,Spell_Code,Birthday,Empl_Type,Work_Name,Clinic_Diagnose,"
                 "Dept_Code,Dept_Name,Paykind_Code,Pact_Code,Pact_Name,Bed_No,In_Date,"
                 "In_Diagnosedate,In_Diagnose,In_Diagnosename,Oper_Code,Oper_Date,"
                 "Reg_No,Fee_Times,Hos_Cost,Year_Cost,Out_Date,Out_Diagnose,"
                 "Out_Diagnosename,Balance_Date,Tot_Cost,Pay_Cost,Pub_Cost,Item_Paycost,"
                 "Base_Cost,Item_Ylcost,Item_Paycost2,Own_Cost,Over_Cost,Valid_Flag,"
                 "Balance_State,Remark,Official_Cost,Type_Code,Person_Type,"
                 "Primarydiagnosecode,Operatecode1,Operatecode2,Operatecode3,"
                 "Primarydiagnosename,overtake_owncost,BUSINESSSEQUENCE,"
                 "SERIOUSILLNESS_IN_COST,SERIOUSILLNESS_COST,SERIOUSILLNESS_TOTAL"
                 ") values("
                 "'" + ret2207setlinfo.value("insutype").toString() + "',"
                 "'" + ret2207setlinfo.value("clr_type").toString() + "',"
                 "'" + ret2207setlinfo.value("clr_way").toString() + "',"
                 "'" + QString::asprintf("%.2f",ret2207setlinfo.value("hifp_pay").toDouble()) + "',"
                 "'" + ret2207setlinfo.value("med_type").toString() + "',"
                 "'" + QString::asprintf("%.2f",ret2207setlinfo.value("medfee_sumamt").toDouble()) + "',"
                 "'" + QString::asprintf("%.2f",ret2207setlinfo.value("preselfpay_amt").toDouble()) + "',"
                 "'" + QString::asprintf("%.2f",ret2207setlinfo.value("inscp_scp_amt").toDouble()) + "',"
                 "'" + QString::asprintf("%.2f",ret2207setlinfo.value("psn_cash_pay").toDouble()) + "',"
                 "'" + QString::asprintf("%.2f",ret2207setlinfo.value("fund_pay_sumamt").toDouble()) + "',"
                 "'" + QString::asprintf("%.2f",ret2207setlinfo.value("acct_pay").toDouble()) + "',"
                 "'" + ret2207setlinfo.value("psn_type").toString() + "',"

                 "'" + personInsuinfo.value("insuplc_admdvs").toString() + "',"
                 "'" + ret2201.value("psn_no").toString() + "',"
                 "'" + ret2201.value("mdtrt_id").toString() + "',"
                 "'" + ret2201.value("ipt_otp_no").toString() + "',"
                 "'" + msgid2207 + "',"
                 "'" + ret2207setlinfo.value("setl_id").toString() + "',"
                 "'" + mdtrt_cert_type + "',"
                 ":individualbalance,:trans_type,:Inpatient_No,"
                 ":Balance_No,:Invoice_No,'11','',"
                 ":Card_No,:Mcard_No,'0','',To_Date('0001/1/1', 'YYYY-MM-DD'),'',"
                 ":Name,:Sex_Code,:Idenno,'',:Birthday,'','','',:Dept_Code,"
                 ":Dept_Name,:Paykind_Code,:Pact_Code,:Pact_Name,'',sysdate,"
                 "sysdate,'','',:Oper_Code,sysdate,:Reg_No,0,0,"
                 ":Year_Cost,sysdate,:Out_Diagnose,:Out_Diagnosename,"
                 "To_Date('0001/1/1', 'yyyy-mm-dd'),:Tot_Cost,:Pay_Cost,"
                 "0,:Item_Paycost,:Base_Cost,:Item_Ylcost,:Item_Paycost2,"
                 ":Own_Cost, 0, '1', '1',:Remark,'0','1',:Person_Type,'','','','','',"
                 "'0','',0,0,0)");
    qro->bindValue(":trans_type",mpPerson["trans_type"]);//交易类型，1正2负
    qro->bindValue(":Inpatient_No",mpPerson["Inpatient_No"]);//住院流水号,clinic_code
    qro->bindValue(":Balance_No", QString::number(blance_no));//结算序号
    qro->bindValue(":Invoice_No",mpPerson["Invoice_No"]);//发票号
    qro->bindValue(":Card_No",mpPerson["Card_No"]);//就诊卡号
    qro->bindValue(":Mcard_No",mpPerson["ybGrbh"]);//医疗证号
    qro->bindValue(":Name",mpPerson["ybXm"]);//姓名
    qro->bindValue(":Sex_Code", mpPerson["ybXb"] == "1" ? "M" : "F"); //性别
    qro->bindValue(":Idenno",mpPerson["ybSfzh"]);//身份证号
    qro->bindValue(":Birthday",QDate::fromString(mpPerson["ybCsrq"],"yyyyMMdd"));//生日
    qro->bindValue(":Dept_Code",mpPerson["Dept_Code"]);//科室代码
    qro->bindValue(":Dept_Name",mpPerson["Dept_Name"]); //科室名称
    qro->bindValue(":Paykind_Code","02");//结算类别 1-自费  2-保险
    qro->bindValue(":Pact_Code","2"); //合同代码
    qro->bindValue(":Pact_Name","沈阳市保");//合同单位名称
    qro->bindValue(":Oper_Code",pub::usr_code);//操作员
    qro->bindValue(":Reg_No",mpPerson["ybSbkh"]);//社保卡号
    qro->bindValue(":Year_Cost",0);
    qro->bindValue(":Out_Diagnose","");
    qro->bindValue(":Out_Diagnosename","");
    qro->bindValue(":Tot_Cost",mpPerson["Tot_Cost"]);//合计金额
    qro->bindValue(":Pay_Cost",mpPerson["Pay_Cost"]); //账户支付
    qro->bindValue(":Own_Cost",mpPerson["Own_Cost"]); //个人支付
    qro->bindValue(":Item_Ylcost",0);//乙类
    qro->bindValue(":Remark",mpPerson["ybXzlx"] );//险种类别2100返回
    qro->bindValue(":Person_Type",mpPerson["ybYldylb"]);//医疗待遇类别2100返回
    double y = mpPerson["ybZhye"].toDouble();   //本次交易后个人账户余额
    y = y - mpPerson["Pay_Cost"].toDouble();
    qro->bindValue(":individualbalance", y);

    if(!qro->exec()){
        QMessageBox::information(this,"错误","插入 fin_ipr_siinmaininfo 失败！"+qro->lastError().text());
        qDebug()<<qro->lastError().text();
        return;
    }
}

void Dialog_gh::on_pbExit_clicked()
{
    qDebug()<<"退出挂号";
    this->close();
}

void Dialog_gh::on_pbRePrint_clicked()
{
    if(s.isEmpty()){
        QMessageBox::information(this,"错误","没有可打印的内容！");

        return;
    }
    printOut(s);


}

void Dialog_gh::onTimeOut()
{
    if(ui->lbLastRec->text().isEmpty()){
        ui->lbLastRec->setText(statusMsg);
    }else{
        ui->lbLastRec->setText("");
    }
    qApp->processEvents();  //刷新显示
}

void Dialog_gh::on_pbGhtp_clicked()
{
    //换号
    //update fin_ipr_siinmaininfo ?
    //errors of patient personal information is impossible, other infomation is dispensable

    if(mpPerson["previous_doct_name"] == docName
            && mpPerson["previous_dept_name"] == deptName
            && mpPerson["previous_patient_name"] == ui->leXm->text().trimmed() ){

        QMessageBox::warning(this,"注意","无可变更内容！");
        return;

    }

    QString info ;
    if(mpPerson["previous_patient_name"] != ui->leXm->text().trimmed() ){
        info.append("患者姓名： " + mpPerson["previous_patient_name"] + " -> " + ui->leXm->text().trimmed() +"\n");
    }

    if(mpPerson["previous_dept_name"] != deptName){
        info.append("就诊科室： " + mpPerson["previous_dept_name"] + " -> " + deptName +"\n") ;
    }

    if(mpPerson["previous_doct_name"] != docName){
        info.append("看诊医生： " + mpPerson["previous_doct_name"] + " -> " + docName +"\n") ;
    }
    info.append("确定要进行挂号信息变更？");

    QMessageBox:: StandardButton result= QMessageBox::warning(this, "注意", info, QMessageBox::Yes|QMessageBox::No);
    if(result == QMessageBox::No){
        return;
    }

    sq = "update fin_opr_register set name = '" + ui->leXm->text().trimmed() + "', "
         "dept_code = '" + deptCode + "', dept_name = '" + deptName +
            "',doct_code = '" + docCode + "', doct_name = '" + docName + "' where rowid = '" + mpPerson["rowid"] + "'";
    if(!qro->exec(sq)){
        QMessageBox::warning(this,"注意","挂号变更操作失败！");
    }else{
        QMessageBox::information(this,"注意","挂号变更操作完成！");
    }
    on_pbClrScr_clicked(); //清屏
}

void Dialog_gh::putBaseIn( QJsonObject &in, QString code)
{
    currentMsgid = pub::getYbStrJ(code, regClinicCode);   //
    if(currentMsgid.isEmpty()){
        QThread::msleep(1000);
        currentMsgid = pub::getYbStrJ(code, "CLINIC_CODE");   //
            if(currentMsgid.isEmpty()){
                QMessageBox::information(this,"note",  code + " 申请交易流水号失败！");
            return ; //未能成功申请交易流水号
        }
    }

    currentInfno = code;
    if(code == "2207A"){
        msgid2207 = currentMsgid;
    }
    in.insert("infno", code);
    in.insert( "msgid", currentMsgid);
    in.insert("mdtrtarea_admvs", pub::hos_insuplc);
    if(!personInsuinfo.value("insuplc_admdvs").toString().isEmpty()){
        in.insert("insuplc_admdvs",personInsuinfo.value("insuplc_admdvs").toString());
    }

    in.insert("insuplc_admdvs","210100");
    in.insert("recer_sys_code", "OwnSoft");
    in.insert("dev_no","");
    in.insert("dev_safe_info","");
    in.insert("cainfo", pub::hos_secretcode);
    in.insert("signtype","");
    in.insert("infver", "V1.0");
    in.insert("opter_type", "1");
    in.insert("opter", pub::usr_code);
    in.insert("opter_name", pub::usr_name);
    in.insert("inf_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
    in.insert("fixmedins_code", pub::hos_ybbh);
    in.insert("fixmedins_name", pub::hos_name);
    in.insert("sign_no", pub::sign_no);

}

void Dialog_gh::on_pbYjs_clicked()
{

    QJsonDocument d;    //清空QJsonObject之用
    QJsonObject in; //入参
    QJsonObject inpu,inpud; // 入参 input 段

    putBaseIn(in, "2201");

    inpu.insert("psn_no", personBaseinfo.value("psn_no").toString());   //人员编号
    inpu.insert("insutype", personInsuinfo.value("insutype").toString());   //险种类型
    inpu.insert("begntime",QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));//	开始时间
    inpu.insert("mdtrt_cert_type",mdtrt_cert_type);//	就诊凭证类型
    if(mdtrt_cert_type == "03"){

        if( "1" == pub::getStr(cardInfo,"|",1) ){   //0 社保卡， 1 老医保卡

            //inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",8) + "|" + busiCardInfo);//老医保卡,8卡号9社保号
            if(pub::getStr(cardInfo,"|",8).isEmpty()){
                inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",9) + "|" + busiCardInfo);//老医保卡,8卡号9社保号
            }else{
                inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",8) + "|" + busiCardInfo);//老医保卡,8卡号9社保号
            }

        }else{
            inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",4) + "|" + busiCardInfo);   //社保卡,4卡号3社保号
        }
    }else if(mdtrt_cert_type == "02"){
        inpu.insert("mdtrt_cert_no",pub::getStr(cardInfo,"|",2) + "|" + busiCardInfo);//	就诊凭证编号
    }else if(mdtrt_cert_type == "01"){
        inpu.insert("mdtrt_cert_no", retScan.value("ecToken").toString());//	就诊凭证编号
    }
    inpu.insert("ipt_otp_no", regClinicCode);//	住院/门诊号
    sq = "select si_code, empl_name from com_doctor_compare where empl_code = '" + docCode + "'";
    qro->exec(sq);
    qro->next();
    docCodeYb = qro->value(0).toString();

    inpu.insert("atddr_no", docCodeYb);//	医师编码
    inpu.insert("dr_name", qro->value(1).toString());//	医师姓名
    inpu.insert("dept_code", deptCode);//	科室编码
    inpu.insert("dept_name", deptName );//	科室名称
    inpu.insert("caty", "0");//	科别

    inpud.insert("data",inpu);
    in.insert("input", inpud);

    QJsonDocument indoc ;
    indoc.setObject(in);

    sq = "update com_business set v_in = '" + indoc.toJson(QJsonDocument::Compact) + "'"
         " where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    qDebug()<<currentInfno + " indoc"<<indoc;

    QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
    connect(naManager, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(postRequestFinished(QNetworkReply*)));

    httpSuccess = false;
    httpFinished = false;
    rpl = naManager->post(request, indoc.toJson());
    qDebug()<<"request " + currentInfno + " ...";
    statusMsg = "交易 " + currentInfno + " 。。。";
    while(true){
        QThread::msleep(330);
        if( ui->lbLastRec->text().isEmpty()){
            ui->lbLastRec->setText(statusMsg);
        }else{
            ui->lbLastRec->setText("");
        }
        qApp->processEvents();
        if(httpFinished){
            //disconnect(naManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(postRequestFinished(QNetworkReply*)));
            qDebug()<<"return request 2201 ...";
            break;
        }
    }

    if(!httpSuccess){// failure then stop operation;
        return ;

    }

    in = d.object();
    inpu = d.object();
    inpud = d.object();
    putBaseIn(in, "2203A");

    inpu.insert("mdtrt_id", ret2201.value("mdtrt_id").toString());   //就诊ID
    inpu.insert("psn_no", personBaseinfo.value("psn_no").toString());   //人员编号
    inpu.insert("med_type","12");//	医疗类别
    inpu.insert("begntime", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));//	开始时间

    inpud.insert("mdtrtinfo",inpu);
    //in.insert("input", inpud);

    inpu = d.object();
    //    inpud = d.object();

    inpu.insert("diag_type", "1");   //诊断类别：1 西医主要诊断， 2 中医主病诊断	3 中医主证诊断
    inpu.insert("diag_srt_no", 1);   //诊断排序号
    inpu.insert("diag_code", defaultDeptDiag); //诊断代码
    qro->exec("select aka121 from view_ka19 where rownum = 1 and aka120 = '" + defaultDeptDiag + "'");
    qro->next();
    inpu.insert("diag_name", qro->value(0).toString());//诊断名称
    inpu.insert("diag_dept", deptName);   //诊断科室
    inpu.insert("dise_dor_no", docCodeYb);   //诊断医生编码
    inpu.insert("dise_dor_name", docName);//诊断医生姓名
    inpu.insert("diag_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));//诊断时间
    inpu.insert("vali_flag", "1");//有效标志

    QJsonArray djsar;

    djsar<<inpu;

    inpud.insert("diseinfo", djsar);


    in.insert("input", inpud);

    indoc.setObject(in);
    qDebug()<< currentInfno + " indoc"<<indoc;

    sq = "update com_business set v_in = '" + indoc.toJson(QJsonDocument::Compact) + "'"
         " where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }


    //QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
    //connect(naManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(postRequestFinished(QNetworkReply*)));

    httpSuccess = false;
    httpFinished = false;
    rpl = naManager->post(request, indoc.toJson());
    qDebug()<<"request " + currentInfno + " ...";
    statusMsg = "交易 " + currentInfno + " 。。。";
    while(true){
        QThread::msleep(330);
        if( ui->lbLastRec->text().isEmpty()){
            ui->lbLastRec->setText(statusMsg);
        }else{
            ui->lbLastRec->setText("");
        }
        qApp->processEvents();
        if(httpFinished){
            //disconnect(naManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(postRequestFinished(QNetworkReply*)));
            qDebug()<<"return request " + currentInfno + " ...";
            break;
        }
    }

    if(!httpSuccess){// failure then stop operation;
        return ;

    }


    //挂号费用上传
    in = d.object();
    inpu = d.object();
    inpud = d.object();
    putBaseIn(in, "2204");

    QJsonArray jsar;
    QString feedetl_sn = "0";
    qro->exec("select max(Balance_No) from fin_ipr_siinmaininfo "
              " where clinic_code = '" + regClinicCode + "'");
    if(qro->next()){
        feedetl_sn = QString::number(qro->value(0).toInt() + 1);
    }


    inpu.insert("feedetl_sn", feedetl_sn);//	费用明细流水号
    inpu.insert("mdtrt_id", ret2201.value("mdtrt_id").toString());//	就诊ID
    inpu.insert("psn_no", personBaseinfo.value("psn_no").toString());//	人员编号
    inpu.insert("chrg_bchno", "temp");//	收费批次号
    //inpu.insert("rxno", personBaseinfo.value("psn_no").toString());//	处方号
    inpu.insert("rx_circ_flag", "0");//	外购处方标志
    inpu.insert("fee_ocur_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));//	费用发生时间
    qro->exec("select fee_code_center, fee_code_his from FIN_OPR_REGFEEITEM"
              " where fee_name ='诊查费'");
    qro->next();

    inpu.insert("med_list_codg", qro->value(0).toString());//	医疗目录编码-00110200001000003
    inpu.insert("medins_list_codg", qro->value(1).toString() );//	医药机构目录编码
    inpu.insert("det_item_fee_sumamt", ui->leYsk->text().toDouble());//	明细项目费用总额
    inpu.insert("cnt", 1);//	数量
    inpu.insert("pric", ui->leYsk->text().toDouble());//	单价
    inpu.insert("bilg_dept_codg", deptCode);//	开单科室编码
    inpu.insert("bilg_dept_name", deptName);//	开单科室名称
    inpu.insert("bilg_dr_codg", docCodeYb);//	开单医生编码
    inpu.insert("bilg_dr_name", docName);//	开单医师姓名
    inpu.insert("hosp_appr_flag", "1");//	医院审批标志

    jsar.append(inpu);

    inpud.insert("feedetail",jsar);
    in.insert("input", inpud);

    //connect(ybBusiness, SIGNAL(resultReady(int, QString,QString)), this, SLOT(handleRet(int, QString,QString)));

    indoc.setObject(in);
    qDebug()<< currentInfno + " indoc"<<indoc;

    sq = "update com_business set v_in = '" + indoc.toJson(QJsonDocument::Compact) + "'"
         " where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    //QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
    //connect(naManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(postRequestFinished(QNetworkReply*)));


    httpSuccess = false;
    httpFinished = false;
    rpl = naManager->post(request, indoc.toJson());
    qDebug()<<"request " + currentInfno + " ...";
    statusMsg = "交易 " + currentInfno + " 。。。";
    while(true){
        QThread::msleep(330);
        if( ui->lbLastRec->text().isEmpty()){
            ui->lbLastRec->setText(statusMsg);
        }else{
            ui->lbLastRec->setText("");
        }
        qApp->processEvents();
        if(httpFinished){
            // disconnect(naManager, SIGNAL(finished(QNetworkReply*)),  this, SLOT(postRequestFinished(QNetworkReply*)));
            qDebug()<<"retrun request " + currentInfno + " ...";
            break;
        }
    }

    if(!httpSuccess){// failure then stop operation;
        return ;//

    }



    //预结算
    in = d.object();
    inpu = d.object();
    inpud = d.object();
    putBaseIn(in, "2206A");

    inpu.insert("psn_no", personBaseinfo.value("psn_no").toString());//人员编号
    inpu.insert("mdtrt_cert_type", mdtrt_cert_type);//	就诊凭证类型

    if(mdtrt_cert_type == "03"){
        if( "1" == pub::getStr(cardInfo,"|",1) ){   //0 社保卡， 1 老医保卡
            inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",8));//老医保卡,8卡号9社保号
        }else{
            inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",4));   //社保卡,4卡号3社保号
        }
    }else if(mdtrt_cert_type == "02"){

    }else if(mdtrt_cert_type == "01"){

    }

    inpu.insert("med_type", "12");//医疗类别    12,挂号
    inpu.insert("medfee_sumamt", ui->leYsk->text());//	医疗费总额
    inpu.insert("psn_setlway", "01");//	个人结算方式
    inpu.insert("mdtrt_id", ret2201.value("mdtrt_id").toString());//	就诊ID
    inpu.insert("chrg_bchno", "temp");//	收费批次号
    inpu.insert("acct_used_flag","1" );//个人账户使用标志
    inpu.insert("insutype", personInsuinfo.value("insutype").toString());//险种类型

    QJsonObject t;
    t.insert("deve_flag","OwnSoft");
    t.insert("dise_reim_mon","");

    inpu.insert("exp_content", t);//	字段扩展
    inpud.insert("data",inpu);
    in.insert("input", inpud);



    //connect(ybBusiness, SIGNAL(resultReady(int, QString,QString)), this, SLOT(handleRet(int, QString,QString)));

    indoc.setObject(in);
    qDebug()<< currentInfno + " indoc"<<indoc;
        sq = "update com_business set v_in = '" + indoc.toJson(QJsonDocument::Compact) + "'"
             " where jyls = '" + currentMsgid + "'";

        if(!qrm->exec(sq)){
            QMessageBox::information(this,"错误","保存入参日志失败！");
            qDebug()<<sq;
        }

    //QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
    //connect(naManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(postRequestFinished(QNetworkReply*)));


    httpSuccess = false;
    httpFinished = false;
    rpl = naManager->post(request, indoc.toJson());
    qDebug()<<"request " + currentInfno + " ...";
    statusMsg = "交易 " + currentInfno + " 。。。";
    while(true){
        QThread::msleep(330);
        if( ui->lbLastRec->text().isEmpty()){
            ui->lbLastRec->setText(statusMsg);
        }else{
            ui->lbLastRec->setText("");
        }
        qApp->processEvents();
        if(httpFinished){
            //disconnect(naManager, SIGNAL(finished(QNetworkReply*)),this, SLOT(postRequestFinished(QNetworkReply*)));
            qDebug()<<"retrun request " + currentInfno + " ...";
            break;
        }
    }
    statusMsg = "预结：";
    statusMsg.append("账户支出 ");
    statusMsg.append(QString::asprintf("%.2f",ret2206setlinfo.value("acct_pay").toDouble()));
    statusMsg.append("现金支出 ");
    statusMsg.append(QString::asprintf("%.2f",ret2206setlinfo.value("psn_cash_pay").toDouble()));

    ui->lbLastRec->setText(statusMsg);
/*

    //医保结算
    in = d.object();
    inpu = d.object();
    inpud = d.object();
    putBaseIn(in, "2207A");

    inpu.insert("psn_no", personBaseinfo.value("psn_no").toString());//人员编号
    inpu.insert("mdtrt_cert_type", mdtrt_cert_type);//	就诊凭证类型

    if(mdtrt_cert_type == "03"){
        if( "1" == pub::getStr(cardInfo,"|",1) ){   //0 社保卡， 1 老医保卡
            inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",8) + "|" + busiCardInfo);//老医保卡,8卡号9社保号
        }else{
            inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",4) + "|" + busiCardInfo);   //社保卡,4卡号3社保号
        }
    }else if(mdtrt_cert_type == "02"){
        inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",2));
    }else if(mdtrt_cert_type == "01"){
        inpu.insert("mdtrt_cert_no", retScan.value("ecToken").toString());//	就诊凭证编号
    }

    inpu.insert("med_type", "12");//医疗类别    12,挂号
    inpu.insert("medfee_sumamt", 3);//	医疗费总额
    inpu.insert("psn_setlway", "01");//	个人结算方式
    inpu.insert("mdtrt_id", ret2201.value("mdtrt_id").toString());//	就诊ID
    inpu.insert("chrg_bchno", cur_fph);//	收费批次号
    inpu.insert("acct_used_flag","1" );//个人账户使用标志
    inpu.insert("insutype", personInsuinfo.value("insutype").toString());//险种类型


//invono	发票号	字符型	20
//fulamt_ownpay_amt	全自费金额	数值型	16,2
//overlmt_selfpay	超限价金额	数值型	16,2
//preselfpay_amt	先行自付金额	数值型	16,2
//inscp_scp_amt	符合政策范围金额	数值型	16,2



    QJsonObject t;
    t.insert("deve_flag","OwnSoft");
    t.insert("dise_reim_mon","");

    inpu.insert("exp_content", t);//	字段扩展
    inpud.insert("data",inpu);
    in.insert("input", inpud);



    //connect(ybBusiness, SIGNAL(resultReady(int, QString,QString)), this, SLOT(handleRet(int, QString,QString)));

    indoc.setObject(in);
    qDebug()<<" 2207 indoc"<<indoc;

    sq = "update com_business set v_in = '" + indoc.toJson(QJsonDocument::Compact) + "'"
         " where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    //QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
    //connect(naManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(postRequestFinished(QNetworkReply*)));


    httpSuccess = false;
    httpFinished = false;
    rpl = naManager->post(request, indoc.toJson());
    qDebug()<<"request " + currentInfno + " ...";
    statusMsg = "交易 " + currentInfno + " 。。。";
    while(true){
        QThread::msleep(330);
        if( ui->lbLastRec->text().isEmpty()){
            ui->lbLastRec->setText(statusMsg);
        }else{
            ui->lbLastRec->setText("");
        }
        qApp->processEvents();
        if(httpFinished){
            //disconnect(naManager, SIGNAL(finished(QNetworkReply*)),this, SLOT(postRequestFinished(QNetworkReply*)));
            qDebug()<<"retrun request " + currentInfno + " ...";
            break;
        }
    }
    if(httpSuccess){
        return "success";
    }else{
        return "";
    }

    */
}

//idCard identify
bool Dialog_gh::verifyIdCard(const char* idCard){
    if(strlen(idCard) != 18){    //检测当前身份证是否为18位
        return false;
    }else{
        int coefficient[] = {7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};                //身份证前17位对应的系数列表
        char checkCodeList[] = {'1','0','X','9','8','7','6','5','4','3','2'};    //余数所对应的效验码列表
        int Sum = 0;
        int remainder;
        char checkCodeValue;

        for(int i=0;i<17;++i){
            Sum += (idCard[i]-48) * coefficient[i];   //身份证前17位分别与对应的系数相乘之和
        }

        remainder = Sum % 11;  //取余数
        checkCodeValue = checkCodeList[remainder];    //余数只会是[0,10] 计算得到身份证最后一位 效验码

        if(checkCodeValue == 'X'){  //用于效验码是'X'的一些处理
            if(checkCodeValue == std::toupper(idCard[17])){
                return true;
            }else{
                return false;
            }
        }else{
            if(checkCodeValue == idCard[17]){
                return true;
            }else{
                return false;
            }
        }
    }
}



